Skip to content

Instantly share code, notes, and snippets.

@unscriptable
Last active May 25, 2023 13:47
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 unscriptable/24cf68634b2df1de91c5ae228662a476 to your computer and use it in GitHub Desktop.
Save unscriptable/24cf68634b2df1de91c5ae228662a476 to your computer and use it in GitHub Desktop.
Typescript functions to share
/**
* 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