Created
December 18, 2020 11:08
-
-
Save JonCatmull/8993253a9b26dee4b44afd5f5cbfe26a to your computer and use it in GitHub Desktop.
Split an array based on predicate function.
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
/** | |
* Splits array when splitOn function returns true. Matched item will kept and be first in the subsequent child array. | |
* @param items | |
* @param splitOn | |
*/ | |
export const splitArray = <T>( | |
items: T[], | |
splitOn: (item: T) => boolean, | |
keepSplitItem = true | |
): T[][] => { | |
if (!items.length) return []; | |
// split array by separators | |
let master: T[][] = []; | |
let split: T[] = []; | |
items.forEach((item) => { | |
if (splitOn(item)) { | |
if (split.length) { | |
master.push(split); | |
} | |
// add matched item to start of new sub split array | |
if (keepSplitItem) { | |
split = [{ ...item }]; | |
} else { | |
split = []; | |
} | |
} else { | |
split.push({ ...item }); | |
} | |
}); | |
// catch any remaining items | |
if (split.length) { | |
master.push(split); | |
} | |
return master; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment