Question 76
Iterator Helpers
ES2025 introduces Iterator Helpers, which provide a set of utility methods that can be chained together to perform operations on iterators in a more readable and functional way. This feature makes working with iterators more convenient and expressive.
// Create a generator function
function* generateNumbers() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}
// Use iterator helpers to transform the values
const result = generateNumbers()[Symbol.iterator]()
.filter(x => x > 1) // Keep only values greater than 1
.map(x => x * 10) // Multiply each value by 10
.take(3) // Take only the first 3 values
.toArray(); // Convert to an array
console.log(result); // [20, 30, 40]
The new Iterator Helper methods include:
- Iterator.prototype.map(): Maps each value in the iterator to a new value.
- Iterator.prototype.filter(): Filters values in the iterator based on a predicate.
- Iterator.prototype.take(): Takes a specified number of values from the iterator.
- Iterator.prototype.drop(): Skips a specified number of values from the iterator.
- Iterator.prototype.flatMap(): Maps each value and flattens the result.
- Iterator.prototype.reduce(): Reduces the iterator to a single value.
- Iterator.prototype.toArray(): Converts the iterator to an array.
- Iterator.prototype.forEach(): Executes a function for each value in the iterator.
- Iterator.prototype.some(): Checks if some values satisfy a condition.
- Iterator.prototype.every(): Checks if all values satisfy a condition.
Iterator Helpers are particularly useful for processing streams of data in a memory-efficient way:
function* generateUserData() {
yield { id: 1, name: "Alice", age: 25 };
yield { id: 2, name: "Bob", age: 30 };
yield { id: 3, name: "Charlie", age: 35 };
yield { id: 4, name: "Dave", age: 40 };
}
// Find users over 30, extract their names, and take the first 2
const olderUserNames = generateUserData()[Symbol.iterator]()
.filter(user => user.age > 30)
.map(user => user.name)
.take(2)
.toArray();
console.log(olderUserNames); // ["Charlie", "Dave"]