https://bigfrontend.dev/problem/implement-range
Can you create a range(from, to) which makes following work?
for (let num of range(1, 4)) {
console.log(num);
}
// 1
// 2
// 3
// 4This is a simple one, could you think more fancy approaches other than for-loop?
Notice that you are not required to return an array, but something iterable would be fine.
/**
* @param {integer} from
* @param {integer} to
*/
function range(from, to) {
// The iterator object that will be returned
// when calling the Symbol.iterator method of an object.
// The iterator object has a method named next which
// generates values for the iteration.
const iterator = {
from: from,
to: to,
next() {
if (this.from > this.to) {
return { done: true };
}
const value = { value: this.from, done: false };
this.from++;
return value;
},
};
// Return an object that has a method named
// Symbol.iterator for the for...of to work.
// When for..of starts, it calls that method once.
return {
[Symbol.iterator]() {
return iterator;
},
};
}