-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathfilter-orderBy.js
70 lines (60 loc) · 1.92 KB
/
filter-orderBy.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
PolymerExpressions.prototype.orderBy = function (array, columnsToOrderBy, reverse) {
if (!Array.isArray(array)) {
return array;
}
if (!columnsToOrderBy) {
return array;
}
if (typeof columnsToOrderBy === 'string') {
columnsToOrderBy = [columnsToOrderBy];
}
// on a column-by-column basis, determine if descending order is desired
var reverseSortValues = [];
columnsToOrderBy.forEach(function (element, index) {
if (element[0] == '-') {
columnsToOrderBy[index] = element.substr(1);
reverseSortValues.push(true);
} else {
reverseSortValues.push(false);
}
});
// temporary holder of position and sort-values
var map = array.map(function (element, index) {
var sortValues = columnsToOrderBy.map(function (key) {
if (typeof element[key] === 'string') {
return element[key].toLowerCase();
}
return element[key];
});
return {
index: index,
sortValues: sortValues
};
});
// sorting the map containing the reduced values
map.sort(function (a, b) {
var length = a.sortValues.length;
for (var i = 0; i < length; i++) {
if (reverseSortValues[i] === false) {
if (a.sortValues[i] < b.sortValues[i])
return -1;
else if (a.sortValues[i] > b.sortValues[i])
return 1;
} else {
if (a.sortValues[i] > b.sortValues[i])
return -1;
else if (a.sortValues[i] < b.sortValues[i])
return 1;
}
}
return 0;
});
if (reverse === true) {
map.reverse();
}
// container for the resulting order
var result = map.map(function (element) {
return array[element.index];
});
return result;
};