Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Created July 10, 2023 10:21
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 JosePedroDias/ea280dbd1662f6c9433777f31ee6a6cb to your computer and use it in GitHub Desktop.
Save JosePedroDias/ea280dbd1662f6c9433777f31ee6a6cb to your computer and use it in GitHub Desktop.
type SortableType = number | string | boolean;
type SortFn<T> = (el: T) => SortableType;
interface SortHelperApi<T> {
sortBy(fn: SortFn<T>, decrescent?: boolean): SortHelperApi<T>;
execute(): T[];
}
/**
* helps sorting arrays
* accepts multiple calls to sortBy (1st takes precedence to 2nd, etc.)
* 2nd argument on sortBy is whether the sorting is in decreasing order
* one must call execute to get back the sorted array (without side-effects on original array)
*/
export function sortHelper<T>(arr: T[]): SortHelperApi<T> {
const sortFns: SortFn<T>[] = [];
const sortDecs: boolean[] = [];
const api: SortHelperApi<T> = {
sortBy(fn: SortFn<T>, decrescent = false) {
sortFns.unshift(fn);
sortDecs.unshift(decrescent);
return api;
},
execute(): T[] {
let finalArr = arr.slice();
let i = 0;
for (const fn of sortFns) {
const dec: boolean = sortDecs[i++];
const arr2: [T, SortableType][] = finalArr.map((el: T) => [el, fn(el)]);
arr2.sort((a_, b_) => {
const a = a_[1];
const b = b_[1];
if (dec) return a > b ? -1 : a < b ? 1 : 0;
return a > b ? 1 : a < b ? -1 : 0;
});
finalArr = arr2.map((el) => el[0]);
}
return finalArr;
},
};
return api;
}
/*
// EXAMPLE USAGE FOLLOWS:
const people = [
{ name: 'john', age: 12, gender: 'm' },
{ name: 'mary', age: 6, gender: 'f' },
{ name: 'mary', age: 21, gender: 'f' },
{ name: 'josh', age: 33, gender: 'm' },
];
const people2 = sortHelper(people)
.sortBy((p) => p.gender)
.sortBy((p) => p.age, true)
.execute();
console.log('people', people);
console.log('people2', people2);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment