diff --git a/packages/arrays/src/bisect.ts b/packages/arrays/src/bisect.ts new file mode 100644 index 0000000000..4f7861b72f --- /dev/null +++ b/packages/arrays/src/bisect.ts @@ -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 = (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 = (src: T[], pred: Predicate) => { + const i = src.findIndex(pred); + return i >= 0 ? bisect(src, i) : [src, []]; +}; diff --git a/packages/arrays/src/index.ts b/packages/arrays/src/index.ts index 2ea51d2581..a04f85dd16 100644 --- a/packages/arrays/src/index.ts +++ b/packages/arrays/src/index.ts @@ -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";