Skip to content

Instantly share code, notes, and snippets.

@monkpit
Created June 1, 2021 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkpit/9b3e27e9e345cb83b0289e44fc84e993 to your computer and use it in GitHub Desktop.
Save monkpit/9b3e27e9e345cb83b0289e44fc84e993 to your computer and use it in GitHub Desktop.
Typed Immutable Sort
export const immutableSort = <T>(array: T[], comparatorFn?: (a: T, b: T) => number): T[] =>
[...array].sort(comparatorFn);
describe('immutableSort', () => {
const testData = [4, 2, 5, -1, 0];
it('can sort an array', () => {
const result = immutableSort(testData);
expect(result).toStrictEqual([-1, 0, 2, 4, 5]);
});
it('does not modify the original array', () => {
const _ = immutableSort(testData);
expect(testData).toStrictEqual([4, 2, 5, -1, 0]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment