This is a simple implementation of lazy evaluation in TypeScript.
Lazy evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed.
First, import the Lazy
class.
import Lazy from '<path-to-src>/index.ts';
You can also import from the dist folder like a module (required build first):
import Lazy from '<path-to-dist>/index.mjs';
Then, create a Lazy instance by calling new Lazy()
.
const lazyValue = new Lazy();
Now you can use the add
method to add a function that will be called when the value is needed. You can add as many functions as you want. The functions will be called in the order they were added.
lazyValue.add((a) => a + 1);
Finally, you can get the value by calling the evaluate
method with the target input.
const result = lazyValue.evaluate([123]); // 124
Creates a new Lazy instance, which models a lazy computation. A Lazy instance has two methods detailed below.
Adds a function to the chain of functions to be evaluated at a later stage. When the function is called it will be called with the remaining arguments supplied to add (if any) followed by a single argument that will be an item from the target array supplied to evaluate.
Name | Type | Description | Required |
---|---|---|---|
fn | Function |
The function to add. | Yes |
arg1...argN-1 | number |
The argument to pass to the function. | No |
argN | number |
The last argument to pass to the function. Value needs to exist in the target when calling evaluate. | No |
Lazy
- The Lazy instance.
Evaluates the lazy value.
Name | Type | Description | Required |
---|---|---|---|
target | number[] |
The input to evaluate. | Yes |
number[]
- The result of the evaluation.
The following examples are available in /examples
.
const lazyValue = new Lazy();
lazyValue.add((a) => a + 1);
const result = lazyValue.evaluate([123]); // [124]
const lazyValue = new Lazy();
lazyValue.add((a) => a + 1);
lazyValue.add((a) => a * 2);
// or lazyValue.add((a) => a + 1).add((a) => a * 2);
const result = lazyValue.evaluate([123]); // [248]
const lazyValue = new Lazy();
lazyValue.add((a, b) => a + b, 10);
const result = lazyValue.evaluate([10, 20]); // [20, 30]
const lazyValue = new Lazy();
lazyValue.add((a, b, c) => a * b + c, -1, 10);
const result = lazyValue.evaluate([10, 20]); // [0, -10]
yarn install
yarn run test
We use Vitest for testing.
yarn run build
More scripts are available in package.json
for misc tasks such as lint, format...
MIT License
JS version available in index-javascript.js
.
TS version available in index.ts
.
TS version with support for strings available in index-generics.ts
.
TS version with cache available in index-cache.ts
. This was just for fun and it doesn't actually work because the functions are not deterministic.