Last active
May 25, 2023 13:47
-
-
Save unscriptable/24cf68634b2df1de91c5ae228662a476 to your computer and use it in GitHub Desktop.
Typescript functions to share
This file contains 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
/** | |
* Separate a list into two lists (left and right) using a predicate to detect | |
* items that should be in the left list. The rest go into the right list. | |
* | |
* @param isLeft - predicate to detect items that should be in the left list | |
* | |
* @returns a function that accepts an array and returns a pair of arrays | |
* | |
* @todo - return type [ L[], R[] ] instead of ambiguous type. | |
*/ | |
const partition | |
= <T>(isLeft: (item: T) => boolean) => (array: T[]): [ T[], T[] ] => | |
array.reduce( | |
([ left, right ], item) => | |
isLeft(item) | |
? [ [ ...left, item ], right ] | |
: [ left, [ ...right, item ] ], | |
[ [], [] ] as [ T[], T[] ] | |
) | |
// Exaample implementation: | |
const partitionStringsFromNulls = partition(x => typeof x === 'string') | |
// Example usage: | |
const [ strings, nulls ] = partitionStringsFromNulls([ 'foo', null, 'bar', 'baz' ])) | |
console.log(strings, nulls) | |
// [ 'foo', 'bar', 'baz' ] [ null ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment