const result = Iter.fromArray([
"apple",
"banana",
"cherry",
"date",
"elderberry",
])
.enumerate()
.map(([index, value]) => [index, value.toUpperCase()])
.filter(([index, value]) => index % 2 === 0)
.take(2)
.intoArray();
This is now published under https://jsr.io/@hoodie/iterators.
Create an iterator from an array and collect all elements into an array.
const array = [1, 2, 3, 4, 5];
const iterator = Iter.fromArray(array);
const result = iterator.intoArray();
console.log(result); // [1, 2, 3, 4, 5]
Create an iterator which yields the current index and the value of the original iterator.
const array = ["a", "b", "c"];
const iterator = Iter.fromArray(array).enumerate();
const result = iterator.intoArray();
console.log(result); // [[0, 'a'], [1, 'b'], [2, 'c']]
Create an iterator skipping all elements which don't meet the given predicate.
const array = [1, 2, 3, 4, 5];
const iterator = Iter.fromArray(array).filter((x) => x % 2 === 0);
const result = iterator.intoArray();
console.log(result); // [2, 4]
Find the first element that satisfies the predicate.
const array = [1, 2, 3, 4, 5];
const iterator = Iter.fromArray(array);
const result = iterator.find((x) => x > 3);
console.log(result); // 4
Create an iterator applying the given callback to each element.
const array = [1, 2, 3];
const iterator = Iter.fromArray(array).map((x) => x * 2);
const result = iterator.intoArray();
console.log(result); // [2, 4, 6]
Create an iterator skipping the first limit
elements.
const array = [1, 2, 3, 4, 5];
const iterator = Iter.fromArray(array).skip(2);
const result = iterator.intoArray();
console.log(result); // [3, 4, 5]
Create an iterator yielding the first limit
elements.
const array = [1, 2, 3, 4, 5];
const iterator = Iter.fromArray(array).take(3);
const result = iterator.intoArray();
console.log(result); // [1, 2, 3]
Create an iterator that โZips upโ two iterators into a single iterator of pairs.
const array1 = [1, 2, 3];
const array2 = ["a", "b", "c"];
const iterator1 = Iter.fromArray(array1);
const iterator2 = Iter.fromArray(array2);
const zipped = iterator1.zip(iterator2);
const result = zipped.intoArray();
console.log(result); // [[1, 'a'], [2, 'b'], [3, 'c']]
Create an iterator that cycles through the elements of the original iterator.
const array = [1, 2, 3];
const iterator = Iter.fromArray(array).cycle();
const result = [];
for (let i = 0; i < 10; i++) {
result.push(iterator.next().value);
}
console.log(result); // [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]