Skip to content

Instantly share code, notes, and snippets.

@trevor-atlas
Last active July 22, 2022 14:35
Show Gist options
  • Save trevor-atlas/a628c91aa4233680ae47eb31b9a4c55b to your computer and use it in GitHub Desktop.
Save trevor-atlas/a628c91aa4233680ae47eb31b9a4c55b to your computer and use it in GitHub Desktop.
A typescript array partitioning helper, split one array into two based on a callback
export const partition = <T>(list: T[], callback: (item: T) => boolean): [T[], T[]] => {
const passed: T[] = [];
const failed: T[] = [];
if (!Array.isArray(list) || list.length === 0) {
return [passed, failed];
}
for (const item of list) {
if (!callback(item)) {
failed.push(item);
} else {
passed.push(item);
}
}
return [passed, failed];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment