Iterable Protocol in JavaScript
Level 5376 keystrokes
Implements the iterable protocol to make a custom Range class work with for...of and spread.
JavaScript code
// Range class represents a sequence of numbers1class Range { // Constructor stores the start and end values2 constructor(start, end) {3 this.start = start;4 this.end = end;5 }6 // Symbol.iterator makes the object iterable // Called when object is used with for...of or spread7 [Symbol.iterator]() { // Track current position in the range8 let current = this.start;9 const end = this.end; // Return an iterator object with next() method10 return { // next() is called for each iteration11 next() { // If we haven't reached the end, return current value12 if (current <= end) { // Return value and increment current, done is false13 return { value: current++, done: false };14 } // When finished, done is true15 return { value: undefined, done: true };16 }17 };18 }19}20 // Create a range from 1 to 521const range = new Range(1, 5);// Spread into array: [1, 2, 3, 4, 5]22console.log([...range]);// Another range: [10, 11, 12]23console.log([...new Range(10, 12)]);Output
[ 1, 2, 3, 4, 5 ] [ 10, 11, 12 ]
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.
.× 13;× 10(× 8)× 8{× 8}× 8=× 6,× 5:× 4[× 3