Created
April 19, 2023 07:53
-
-
Save Radiergummi/ccc83114df365bb5bfd0db619fe8e056 to your computer and use it in GitHub Desktop.
A type-preserving TypeScript helper to partition arrays.
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
/** | |
* 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