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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!