Custom Iterator in JavaScript
Level 5261 keystrokes
Custom iterators implement Symbol.iterator to make objects work with for...of loops.
JavaScript code
// Create an object that can be iterated1const range = { // Define the range boundaries2 from: 1,3 to: 5, // Symbol.iterator makes the object iterable4 [Symbol.iterator]() { // Return an iterator object5 return { // Iterator state6 current: this.from,7 last: this.to, // next() is called on each iteration8 next() { // Check if there are more values9 if (this.current <= this.last) { // Return the current value and increment10 return { done: false, value: this.current++ };11 } // Signal iteration is complete12 return { done: true };13 }14 };15 }16};17 // for...of uses the iterator automatically18for (const n of range) console.log(n);Output
1 2 3 4 5
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
:× 7.× 7{× 7}× 7,× 5;× 5(× 5)× 5+× 2=× 2