UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

62 lines (61 loc) 1.6 kB
import { _stringMapValues, } from '../types.js'; class Comparators { /** * Good for numbers. */ numericAsc(a, b) { return a - b; } numericDesc(a, b) { return b - a; } localeAsc(a, b) { return a.localeCompare(b); } localeDesc(a, b) { return -a.localeCompare(b); } by(mapper, opt = {}) { const mod = opt.dir === 'desc' ? -1 : 1; return (objA, objB) => { // This implementation may call mapper more than once per item, // but the benchmarks show no significant difference in performance. const a = mapper(objA); const b = mapper(objB); if (a > b) return mod; if (a < b) return -mod; return 0; }; } updatedAsc(a, b) { return a.updated - b.updated; } updatedDesc(a, b) { return b.updated - a.updated; } createdAsc(a, b) { return a.created - b.created; } createdDesc(a, b) { return b.created - a.created; } } export const comparators = new Comparators(); /** * _sortBy([{age: 20}, {age: 10}], 'age') * // => [{age: 10}, {age: 20}] * * Same: * _sortBy([{age: 20}, {age: 10}], o => o.age) */ export function _sortBy(items, mapper, opt = {}) { return (opt.mutate ? items : [...items]).sort(comparators.by(mapper, opt)); } /** * Like _stringMapValues, but values are sorted. */ export function _stringMapValuesSorted(map, mapper, dir = 'asc') { return _sortBy(_stringMapValues(map), mapper, { dir }); }