How deferred execution works in itiriri
masterUnlike standard JavaScript array methods that create shallow copies and execute immediately, itiriri functions that return iterables use deferred execution.
Key behaviors:
- Lazy Evaluation: The source iterable is not processed until you chain a function that reduces the value (like
.sum()) or transform it into a built-in type (like iterating withfor...of). - Single Pass: The source iterable is iterated only once.
- Memory Efficiency: Methods like
filter,map, andconcatdo not buffer elements; they pipe them one-by-one through the chain. - Infinite Iterables: Because of deferred execution, you can use itiriri with infinite generators (e.g., a Fibonacci sequence) as long as you use a terminal method like
.take(n)to limit the results.
Note: Functions that require the entire sequence to be known (like sort, reverse, or shuffle) expect a finite iterable.
import itiriri from 'itiriri';
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
// Finding first 3 Fibonacci numbers that contain '42'
// This works because .take(3) stops the iteration
const result = itiriri(fibonacci())
.filter(x => x.toString().indexOf('42') !== -1)
.take(3);
for (const e of result) {
console.log(e);
}
// outputs: 514229, 267914296, 7778742049