Skip to content

Instantly share code, notes, and snippets.

@RobinBuschmann
Created December 7, 2020 09:17
Show Gist options
  • Save RobinBuschmann/978c7830c14aa98688ffd61826dc0964 to your computer and use it in GitHub Desktop.
Save RobinBuschmann/978c7830c14aa98688ffd61826dc0964 to your computer and use it in GitHub Desktop.
/**
* @example
* ```ts
* const [selectedItems, nonSelectedItems] = partition(array, item => item.selected);
* const [
* numsLessThan5,
* numsLessThan10,
* numsLessThan30,
* numsGreaterEquals30
* ] = partition(
* numbers,
* num => num < 5,
* num => num < 10,
* num => num < 30,
* );
* ```
*/
export const partition = <T>(arr: T[], ...filters: Array<(item: T) => boolean>): T[][] => {
filters = [...filters, () => true];
return arr.reduce(
(partitions, item) => {
for (let i = 0; i < filters.length; i++) {
if (filters[i](item)) {
partitions[i].push(item);
break;
}
}
return partitions;
},
filters.map(() => [] as T[]),
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment