Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,5 @@
"ts-node": "^9.1.1",
"typescript": "^5.3.3"
},
"packageManager": "yarn@4.4.0"
"packageManager": "yarn@4.9.1"
}
11 changes: 11 additions & 0 deletions src/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
toggleElement,
withoutIndex,
makeNumberCompareFn,
makeBooleanCompareFn,
} from './array';
import { Maybe } from './types';

Expand Down Expand Up @@ -283,6 +284,16 @@ describe('makeNumberCompareFn', () => {
});
});

describe('makeBooleanCompareFn', () => {
type KeyBoolean = { key: boolean };

it('creates a compare function that sorts booleans', () => {
const compareFn = makeBooleanCompareFn<KeyBoolean>((record) => record.key);
const original: Array<KeyBoolean> = [{ key: true }, { key: false }];
expect(original.sort(compareFn)).toEqual([{ key: false }, { key: true }]);
});
});

describe('localeCompareStrings', () => {
it('sorts strings', () => {
const original: Array<string> = ['c', '', 'a', 'b'];
Expand Down
15 changes: 15 additions & 0 deletions src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,21 @@ export function makeNumberCompareFn<TSortable>(
};
}

/**
* 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<TSortable>(
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.
Expand Down