LearnFrenzy
Sign in Take a free test

ES6 Features · ES6 Features Coding Problems · Question 5

An iterable Range class in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Write a Range class (start, end, step) that works with for…of, spread and Array.from, supports negative steps, and has an includes method.

Solution
main.js
class Range {
  constructor(start, end, step = 1) {
    if (step === 0) throw new RangeError("step cannot be 0");
    Object.assign(this, { start, end, step });
  }
  *[Symbol.iterator]() {
    for (let x = this.start; this.step > 0 ? x <= this.end : x >= this.end; x += this.step) yield x;
  }
  includes(n) { return [...this].includes(n); }
}

console.log([...new Range(1, 10, 3)]);
console.log(Array.from(new Range(10, 0, -5)), new Range(0, 20, 5).includes(15));
let sum = 0;
for (const n of new Range(1, 100)) sum += n;
console.log(sum);

Output Verified by running it on Node.js

[ 1, 4, 7, 10 ]
[ 10, 5, 0 ] true
5050

A generator method named [Symbol.iterator] makes every Range iterable. The loop condition flips for negative steps, and step 0 is rejected because it would never end.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links