Skip to content

Commit

Permalink
feat(arrays): add bisect(), bisectWith()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Dec 29, 2020
1 parent 971d5dc commit 17d06a4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/arrays/src/bisect.ts
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, []];
};
1 change: 1 addition & 0 deletions packages/arrays/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from "./api";
export * from "./binary-search";
export * from "./bisect";
export * from "./ends-with";
export * from "./ensure-array";
export * from "./ensure-iterable";
Expand Down

0 comments on commit 17d06a4

Please sign in to comment.