Skip to content

Commit 7d61e5c

Browse files
committed
feat: add makeBooleanCompareFn
1 parent ee3a184 commit 7d61e5c

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,5 +79,5 @@
7979
"ts-node": "^9.1.1",
8080
"typescript": "^5.3.3"
8181
},
82-
"packageManager": "yarn@4.4.0"
82+
"packageManager": "yarn@4.9.1"
8383
}

src/array.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
toggleElement,
1313
withoutIndex,
1414
makeNumberCompareFn,
15+
makeBooleanCompareFn,
1516
} from './array';
1617
import { Maybe } from './types';
1718

@@ -283,6 +284,16 @@ describe('makeNumberCompareFn', () => {
283284
});
284285
});
285286

287+
describe('makeBooleanCompareFn', () => {
288+
type KeyBoolean = { key: boolean };
289+
290+
it('creates a compare function that sorts booleans', () => {
291+
const compareFn = makeBooleanCompareFn<KeyBoolean>((record) => record.key);
292+
const original: Array<KeyBoolean> = [{ key: true }, { key: false }];
293+
expect(original.sort(compareFn)).toEqual([{ key: false }, { key: true }]);
294+
});
295+
});
296+
286297
describe('localeCompareStrings', () => {
287298
it('sorts strings', () => {
288299
const original: Array<string> = ['c', '', 'a', 'b'];

src/array.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,21 @@ export function makeNumberCompareFn<TSortable>(
127127
};
128128
}
129129

130+
/**
131+
* Takes a function that maps the values to sort to booleans and returns a compare function that puts `false` before `true`.
132+
* Usable in `Array.toSorted` or similar APIs.
133+
*/
134+
export function makeBooleanCompareFn<TSortable>(
135+
map: (sortable: TSortable) => boolean,
136+
): (a: TSortable, b: TSortable) => number {
137+
return (a, b) => {
138+
const mappedA = map(a);
139+
const mappedB = map(b);
140+
141+
return Number(mappedA) - Number(mappedB);
142+
};
143+
}
144+
130145
/**
131146
* Returns a compare function for values that are string, null or undefined,
132147
* using `String.prototype.localeCompare`, usable in `Array.toSorted` or similar APIs.

0 commit comments

Comments
 (0)