Skip to content

Instantly share code, notes, and snippets.

@Radiergummi
Created April 19, 2023 07:53
Show Gist options
  • Save Radiergummi/ccc83114df365bb5bfd0db619fe8e056 to your computer and use it in GitHub Desktop.
Save Radiergummi/ccc83114df365bb5bfd0db619fe8e056 to your computer and use it in GitHub Desktop.
A type-preserving TypeScript helper to partition arrays.
/**
* Partition an array into two arrays based on a predicate.
*
* @param array
* @param isValid
*/
export function partition<T, V>( array: ( T | V )[], isValid: ( x: T | V ) => x is T ): [ T[], V[] ] {
return array.reduce( ( [ pass, fail ], elem ) => {
return isValid( elem ) ? [ [ ...pass, elem ], fail ] : [ pass, [ ...fail, elem ] ];
}, [ [] as T[], [] as V[] ] );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment