Custom Iterator Protocol in JavaScript
Level 5245 keystrokes
Implementing Symbol.iterator allows custom objects to be used with for-of loops and spread operator.
JavaScript code
// Create range object with iterator1const range = { // Define start value2 start: 1, // Define end value3 end: 5, // Implement the iterator protocol4 [Symbol.iterator]() { // Initialize current to start5 let current = this.start; // Store end value6 const end = this.end; // Return iterator object7 return { // next() returns iteration result8 next() { // If current is within range9 if (current <= end) { // Return value and increment10 return { value: current++, done: false };11 } // Signal iteration complete12 return { done: true };13 }14 };15 }16};// The spread operator calls the iterator until done: [1, 2, 3, 4, 5]17console.log([...range]);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(× 4)× 4=× 4,× 3[× 2