Package: effect
Module: Array
The “do simulation” for array allows you to sequentially apply operations to the elements of arrays, just as nested loops allow you to go through all combinations of elements in an arrays.
It can be used to simulate “array comprehension”. It’s a technique that allows you to create new arrays by iterating over existing ones and applying specific conditions or transformations to the elements. It’s like assembling a new collection from pieces of other collections based on certain rules.
Here’s how the do simulation works:
Do valuebind function to define variables and bind them to Array valuesbind statements to define multiple variables within the scopelet function to define variables and bind them to simple valuesArray functions like map and filter can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scopeExample
import { Array, pipe } from "effect"
const doResult = pipe(
Array.Do,
Array.bind("x", () => [1, 3, 5]),
Array.bind("y", () => [2, 4, 6]),
Array.filter(({ x, y }) => x < y), // condition
Array.map(({ x, y }) => [x, y] as const) // transformation
)
console.log(doResult) // [[1, 2], [1, 4], [1, 6], [3, 4], [3, 6], [5, 6]]
// equivalent
const x = [1, 3, 5],
y = [2, 4, 6],
result = [];
for(let i = 0; i < x.length; i++) {
for(let j = 0; j < y.length; j++) {
const _x = x[i], _y = y[j];
if(_x < _y) result.push([_x, _y] as const)
}
}
See
bindToDoletSignature
declare const bind: { <A extends object, N extends string, B>(tag: Exclude<N, keyof A>, f: (a: NoInfer<A>) => ReadonlyArray<B>): (self: ReadonlyArray<A>) => Array<{ [K in N | keyof A]: K extends keyof A ? A[K] : B; }>; <A extends object, N extends string, B>(self: ReadonlyArray<A>, tag: Exclude<N, keyof A>, f: (a: NoInfer<A>) => ReadonlyArray<B>): Array<{ [K in N | keyof A]: K extends keyof A ? A[K] : B; }>; }
Since v3.2.0