-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
73 lines (64 loc) · 1.82 KB
/
index.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
var objectPath = require('object-path');
var sortBy;
var sort;
var type;
/**
* Filters args based on their type
* @param {String} type Type of property to filter by
* @return {Function}
*/
type = function(type) {
return function(arg) {
return typeof arg === type;
};
};
/**
* Return a comparator function
* @param {String} property The key to sort by
* @param {Function} map Function to apply to each property
* @return {Function} Returns the comparator function
*/
sort = function sort(property, map) {
var sortOrder = 1;
var apply = map || function(_, value) { return value };
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function fn(a,b) {
var result;
var am = apply(property, objectPath.get(a, property));
var bm = apply(property, objectPath.get(b, property));
if (am < bm) result = -1;
if (am > bm) result = 1;
if (am === bm) result = 0;
return result * sortOrder;
}
};
/**
* Return a comparator function that sorts by multiple keys
* @return {Function} Returns the comparator function
*/
sortBy = function sortBy() {
var args = Array.prototype.slice.call(arguments);
var properties = args.filter(type('string'));
var map = args.filter(type('function'))[0];
return function fn(obj1, obj2) {
var numberOfProperties = properties.length,
result = 0,
i = 0;
/* try getting a different result from 0 (equal)
* as long as we have extra properties to compare
*/
while(result === 0 && i < numberOfProperties) {
result = sort(properties[i], map)(obj1, obj2);
i++;
}
return result;
};
};
/**
* Expose `sortBy`
* @type {Function}
*/
module.exports = sortBy;