Created
November 14, 2023 16:31
-
-
Save pjflanagan/05a96856b911da57f35fa745c3fbd4eb to your computer and use it in GitHub Desktop.
A util function like filter that also returns an array that doesn't match
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
type Split<T> = [T[], T[]]; | |
export function split<T>(arr: T[], isMatch: (item: T) => boolean): Split<T> { | |
return arr.reduce<Split<T>>((rv: [T[], T[]], item: T) => { | |
if (isMatch(item)) { | |
rv[0] = [...rv[0], item]; | |
} else { | |
rv[1] = [...rv[1], item]; | |
} | |
return rv; | |
}, [[], []] as Split<T>); | |
} | |
const [match, noMatch] = split([1,2,3,4,5], (i) => i % 2 === 0); | |
// match = [2, 4] | |
// noMatch = [1, 3, 5] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment