-
-
Notifications
You must be signed in to change notification settings - Fork 153
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(arrays): add bisect(), bisectWith()
- Loading branch information
1 parent
971d5dc
commit 17d06a4
Showing
2 changed files
with
27 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import type { Predicate } from "@thi.ng/api"; | ||
|
||
/** | ||
* Splits array at given index (default: floor(src.length/2)) and returns tuple of [lhs, rhs]. | ||
* | ||
* @param src | ||
* @param i | ||
*/ | ||
export const bisect = <T>(src: T[], i = src.length >>> 1) => [ | ||
src.slice(0, i), | ||
src.slice(i), | ||
]; | ||
|
||
/** | ||
* Similar to {@link bisect}, but first finds split index via provided | ||
* predicate. The item for which the predicate first returns a truthy result, | ||
* will be the first item in the RHS array. If the predicate never succeeds, the | ||
* function returns `[src, []]`, i.e. all items will remain in the LHS. | ||
* | ||
* @param src | ||
* @param pred | ||
*/ | ||
export const bisectWith = <T>(src: T[], pred: Predicate<T>) => { | ||
const i = src.findIndex(pred); | ||
return i >= 0 ? bisect(src, i) : [src, []]; | ||
}; |
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