|
| 1 | +/** |
| 2 | + * Utility functions that are not used anywhere, to have handy when needed |
| 3 | + */ |
| 4 | + |
| 5 | +/** Copy methods from one class onto another */ |
| 6 | +export function extend (Class, Mixin) { |
| 7 | + let members = Object.getOwnPropertyDescriptors(Mixin.prototype); |
| 8 | + |
| 9 | + for (let key in members) { |
| 10 | + if (key in Class.prototype) { |
| 11 | + continue; |
| 12 | + } |
| 13 | + |
| 14 | + Object.defineProperty(Class.prototype, key, members[key]); |
| 15 | + } |
| 16 | + |
| 17 | + let statics = Object.getOwnPropertyDescriptors(Mixin); |
| 18 | + |
| 19 | + for (let key in statics) { |
| 20 | + if (key in Class) { |
| 21 | + continue; |
| 22 | + } |
| 23 | + |
| 24 | + Object.defineProperty(Class, key, statics[key]); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +export const sort = { |
| 29 | + alphanumeric: (a, b) => a.localeCompare(b), |
| 30 | + alphanumericDesc: (a, b) => b.localeCompare(a), |
| 31 | + numeric: (a, b) => a - b, |
| 32 | + numericDesc: (a, b) => b - a, |
| 33 | + count: (a, b) => a.length - a.length, |
| 34 | + countDesc: (a, b) => b.length - a.length, |
| 35 | +}; |
| 36 | + |
| 37 | +export function groupBy (arr, fn) { |
| 38 | + let grouped = new Map(); |
| 39 | + let isFunction = typeof fn === 'function'; |
| 40 | + |
| 41 | + for (let item of arr) { |
| 42 | + let key = isFunction ? fn(item) : item[fn]; |
| 43 | + let items = grouped.get(key); |
| 44 | + |
| 45 | + if (!items) { |
| 46 | + items = []; |
| 47 | + grouped.set(key, items); |
| 48 | + } |
| 49 | + |
| 50 | + items.push(item); |
| 51 | + } |
| 52 | + |
| 53 | + // if (sortValues) { |
| 54 | + // grouped = sortObjectValues(grouped, sortValues); |
| 55 | + // } |
| 56 | + // else if (sortKeys) { |
| 57 | + // grouped = sortObjectKeys(grouped, sortKeys); |
| 58 | + // } |
| 59 | + |
| 60 | + return grouped; |
| 61 | +} |
| 62 | + |
| 63 | +export function sortObjectKeys (obj, fn = sort.alphanumeric) { |
| 64 | + let sortedKeys = Object.keys(obj).sort(fn); |
| 65 | + let sortedObj = {}; |
| 66 | + |
| 67 | + for (let key of sortedKeys) { |
| 68 | + sortedObj[key] = obj[key]; |
| 69 | + } |
| 70 | + |
| 71 | + return sortedObj; |
| 72 | +} |
| 73 | + |
| 74 | +export function sortObjectValues (obj, fn = sort.countDesc) { |
| 75 | + let sortedEntries = Object.entries(obj).sort((a, b) => fn(a[1], b[1])); |
| 76 | + let sortedObj = {}; |
| 77 | + |
| 78 | + for (let [key, value] of sortedEntries) { |
| 79 | + sortedObj[key] = value; |
| 80 | + } |
| 81 | + |
| 82 | + return sortedObj; |
| 83 | +} |
0 commit comments