typed-utilities
Version:
Strongly typed general purpose utilities
50 lines (38 loc) • 1.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sortByProperty = void 0;
// "sortByProperty" is memoized; instead of creating a new function each time it is called.
// However inner functions (returned by sortBy) are not.
const sortByPropertyFnCache = {}; // Example usage: [{ x: "b" }, { x: "a" }].sort(sortBy("x")) is [{ x: "a" }, { x: "b" }]
const sortByProperty = (...keys) => {
const cacheIndex = JSON.stringify(keys);
if (!sortByPropertyFnCache[cacheIndex]) {
sortByPropertyFnCache[cacheIndex] = (a, b) => {
if (keys.length === 0) {
return 0;
}
const [key, ...rest] = keys;
const ak = a[key];
const bk = b[key];
if (typeof ak !== `string` && typeof bk !== `string`) {
return 0;
}
if (typeof ak !== `string`) {
return -1;
}
if (typeof bk !== `string`) {
return 1;
}
const value = ak.localeCompare(bk);
if (value !== 0) {
return value;
}
return sortByProperty(...rest)(a, b);
};
}
return sortByPropertyFnCache[cacheIndex];
};
exports.sortByProperty = sortByProperty;
//# sourceMappingURL=sortByProperty.js.map