|
@@ -17,28 +17,62 @@ const isObject = function(obj) {
|
|
|
return obj !== null && typeof obj === 'object';
|
|
|
};
|
|
|
|
|
|
-export const orderBy = function(array, sortKey, reverse, sortMethod) {
|
|
|
+export const orderBy = function(array, sortKey, reverse, sortMethod, sortBy) {
|
|
|
+ if (!sortKey && !sortMethod && (!sortBy || Array.isArray && !sortBy.length)) {
|
|
|
+ return array;
|
|
|
+ }
|
|
|
if (typeof reverse === 'string') {
|
|
|
reverse = reverse === 'descending' ? -1 : 1;
|
|
|
+ } else {
|
|
|
+ reverse = (reverse && reverse < 0) ? -1 : 1;
|
|
|
}
|
|
|
- if (!sortKey && !sortMethod) {
|
|
|
- return array;
|
|
|
- }
|
|
|
- const order = (reverse && reverse < 0) ? -1 : 1;
|
|
|
-
|
|
|
- // sort on a copy to avoid mutating original array
|
|
|
- return array.slice().sort(sortMethod ? function(a, b) {
|
|
|
- const result = sortMethod(a, b);
|
|
|
- return result === 0 ? 0 : result > 0 ? order : -order;
|
|
|
- } : function(a, b) {
|
|
|
+ const getKey = sortMethod ? null : function(value, index) {
|
|
|
+ if (sortBy) {
|
|
|
+ if (!Array.isArray) {
|
|
|
+ sortBy = [sortBy];
|
|
|
+ }
|
|
|
+ return sortBy.map(function(by) {
|
|
|
+ if (typeof by === 'string') {
|
|
|
+ return getValueByPath(value, by);
|
|
|
+ } else {
|
|
|
+ return by(value, index, array);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
if (sortKey !== '$key') {
|
|
|
- if (isObject(a) && '$value' in a) a = a.$value;
|
|
|
- if (isObject(b) && '$value' in b) b = b.$value;
|
|
|
+ if (isObject(value) && '$value' in value) return [value.$value];
|
|
|
+ } else {
|
|
|
+ return [isObject(value) ? getValueByPath(value, sortKey) : value];
|
|
|
}
|
|
|
- a = isObject(a) ? getValueByPath(a, sortKey) : a;
|
|
|
- b = isObject(b) ? getValueByPath(b, sortKey) : b;
|
|
|
- return a === b ? 0 : a > b ? order : -order;
|
|
|
- });
|
|
|
+ };
|
|
|
+ const compare = function(a, b) {
|
|
|
+ if (sortMethod) {
|
|
|
+ return sortMethod(a.value, b.value);
|
|
|
+ }
|
|
|
+ for (let i = 0, len = a.key.length; i < len; i++) {
|
|
|
+ if (a.key[i] < b.key[i]) {
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+ if (a.key[i] > b.key[i]) {
|
|
|
+ return 1;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return 0;
|
|
|
+ };
|
|
|
+ return array.map(function(value, index) {
|
|
|
+ return {
|
|
|
+ value: value,
|
|
|
+ index: index,
|
|
|
+ key: getKey ? getKey(value, index) : null
|
|
|
+ };
|
|
|
+ }).sort(function(a, b) {
|
|
|
+ let order = compare(a, b);
|
|
|
+ if (!order) {
|
|
|
+ // make stable https://en.wikipedia.org/wiki/Sorting_algorithm#Stability
|
|
|
+ order = a.index - b.index;
|
|
|
+ }
|
|
|
+ return order * reverse;
|
|
|
+ }).map(item => item.value);
|
|
|
};
|
|
|
|
|
|
export const getColumnById = function(table, columnId) {
|