diff --git a/package.json b/package.json index c38a984..08a315c 100644 --- a/package.json +++ b/package.json @@ -79,5 +79,5 @@ "ts-node": "^9.1.1", "typescript": "^5.3.3" }, - "packageManager": "yarn@4.4.0" + "packageManager": "yarn@4.9.1" } diff --git a/src/array.test.ts b/src/array.test.ts index 4b8eb57..0b67cbf 100644 --- a/src/array.test.ts +++ b/src/array.test.ts @@ -12,6 +12,7 @@ import { toggleElement, withoutIndex, makeNumberCompareFn, + makeBooleanCompareFn, } from './array'; import { Maybe } from './types'; @@ -283,6 +284,16 @@ describe('makeNumberCompareFn', () => { }); }); +describe('makeBooleanCompareFn', () => { + type KeyBoolean = { key: boolean }; + + it('creates a compare function that sorts booleans', () => { + const compareFn = makeBooleanCompareFn((record) => record.key); + const original: Array = [{ key: true }, { key: false }]; + expect(original.sort(compareFn)).toEqual([{ key: false }, { key: true }]); + }); +}); + describe('localeCompareStrings', () => { it('sorts strings', () => { const original: Array = ['c', '', 'a', 'b']; diff --git a/src/array.ts b/src/array.ts index ec3265f..7be0b02 100644 --- a/src/array.ts +++ b/src/array.ts @@ -127,6 +127,21 @@ export function makeNumberCompareFn( }; } +/** + * Takes a function that maps the values to sort to booleans and returns a compare function that puts `false` before `true`. + * Usable in `Array.toSorted` or similar APIs. + */ +export function makeBooleanCompareFn( + map: (sortable: TSortable) => boolean, +): (a: TSortable, b: TSortable) => number { + return (a, b) => { + const mappedA = map(a); + const mappedB = map(b); + + return Number(mappedA) - Number(mappedB); + }; +} + /** * Returns a compare function for values that are string, null or undefined, * using `String.prototype.localeCompare`, usable in `Array.toSorted` or similar APIs.