UNPKG

@newdash/newdash

Version:

javascript/typescript utility library

65 lines (64 loc) 1.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.hashSort = void 0; /* eslint-disable max-len */ const identity_1 = require("./.internal/identity"); const isEmpty_1 = require("./isEmpty"); const toString_1 = require("./toString"); /** * hash sort function * * @since 5.21.0 * @param collection array collection * @param indexer extract numeric index from each item of collection * @param reverse reverse the sort order (DESC) * @returns the sorted list * * @example * * ```js * hashSort([2, 999, 3, 113, 3, 32, 3, 4]) * // [2, 3, 3, 3, 4, 32, 113, 999] * * hashSort( [ { age: 2 },{ age: 999 },{ age: 3 }, { age: 113 },{ age: 3 },{ age: 32 }, { age: 3 },{ age: 4 } ], (item) => item.age ) // [ // { age: 2 },{ age: 3 },{ age: 3 }, // { age: 3 },{ age: 4 },{ age: 32 }, // { age: 113 },{ age: 999 } // ] * ``` */ function hashSort(collection, indexer, reverse = false) { const hashTable = []; if (indexer === undefined) { // @ts-ignore indexer = identity_1.identity; } for (const item of collection) { const index = indexer(item); if (typeof index !== "number") { throw new TypeError(`for the value ${(0, toString_1.toString)(item)}, the indexer function return the ${typeof indexer} value, expected: number`); } if (index < 0) { throw new Error(`for the value ${(0, toString_1.toString)(item)}, the indexer function return the value ${index}, expected number greater or equal then 0`); } if (hashTable[index] === undefined) { hashTable[index] = []; } hashTable[index].push(item); } let tmpArr = hashTable.filter((list) => !(0, isEmpty_1.isEmpty)(list)); if (reverse) { tmpArr = tmpArr.reverse(); } return tmpArr.reduce((pre, cur) => { pre.push(...cur); return pre; }, []); } exports.hashSort = hashSort; exports.default = hashSort;