跳到主要内容

bifurcateBy

TS JS Deno

Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.

Use Array.prototype.reduce() and Array.prototype.push() to add elements to groups, based on the value returned by fn for each element.

typescript
type Predicate<T> = (item: T) => boolean;

const bifurcateBy = <T = any>(arr: T[], filter: Predicate<T>) =>
arr.reduce(
(acc, val) => {
acc[filter(val) ? 0 : 1].push(val);
return acc;
},
[[] as T[], [] as T[]]
);
typescript
bifurcateBy(["beep", "boop", "foo", "bar"], (x: string) => x[0] === "b"); // [ ['beep', 'boop', 'bar'], ['foo'] ]

// To Get Filtered(falsy) values

const [filtered] = bifurcateBy(["beep", "boop", undefined, null, 1], Boolean); // filtered == ["beep", "boop", 1]

assertEquals(
bifurcate(["beep", "boop", "foo", "bar"], (item: string) =>
item.startsWith("b")
),
[["beep", "boop", "bar"], ["foo"]]
);