-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathsortBy.js
38 lines (30 loc) · 792 Bytes
/
sortBy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'use strict';
const nestedValue = require('../helpers/nestedValue');
const { isFunction } = require('../helpers/is');
module.exports = function sortBy(valueOrFunction) {
const collection = [].concat(this.items);
const getValue = (item) => {
if (isFunction(valueOrFunction)) {
return valueOrFunction(item);
}
return nestedValue(item, valueOrFunction);
};
collection.sort((a, b) => {
const valueA = getValue(a);
const valueB = getValue(b);
if (valueA === null || valueA === undefined) {
return 1;
}
if (valueB === null || valueB === undefined) {
return -1;
}
if (valueA < valueB) {
return -1;
}
if (valueA > valueB) {
return 1;
}
return 0;
});
return new this.constructor(collection);
};