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 numbers
1class Range {
// Constructor stores the start and end values
2 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 spread
7 [Symbol.iterator]() {
// Track current position in the range
8 let current = this.start;
9 const end = this.end;
// Return an iterator object with next() method
10 return {
// next() is called for each iteration
11 next() {
// If we haven't reached the end, return current value
12 if (current <= end) {
// Return value and increment current, done is false
13 return { value: current++, done: false };
14 }
// When finished, done is true
15 return { value: undefined, done: true };
16 }
17 };
18 }
19}
20
// Create a range from 1 to 5
21const 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

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

More JavaScript examples at level 5

← JavaScript typing practice