Created
December 7, 2020 09:17
-
-
Save RobinBuschmann/978c7830c14aa98688ffd61826dc0964 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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