For mocking some data for tests or fill some array with fake data or whatever, sometimes I miss the python range iterator in Javascript.
myList = [0,1,2,3]
for i in range(0, len(myList))
print i
With the not so new by now specific of Javascript we can "generate" our own iterators.
An implementation of range could be this one:
function range(start = 0, end, step = 1) {
return {
*[Symbol.iterator]() {
let newStart = start,
newEnd = end;
if (end < start) {
newStart = end;
newEnd = start;
}
for (let i = newStart; i < newEnd; i += step) {
yield i;
}
}
};
}
// forward
for (let element of range(0, 10)) {
console.log({ element });
}
// and backwards
for (let element of range(0, -10)) {
console.log({ element });
}
We can write an even simpler implementation just writing the generator function.
function* range(start = 0, end, step = 1) {
let newStart = start,
newEnd = end;
if (end < start) {
newStart = end;
newEnd = start;
}
for (let i = newStart; i < newEnd; i += step) {
yield i;
}
}
// forward
for (let element of range(0, 10)) {
console.log({ element });
}
// and backwards
for (let element of range(0, -10)) {
console.log({ element });
}
Of course you must use the new for-of in order to iterate over it.
Just remember that the function returns always an iterator under the hood. So we can always easily take the iterator in this way if needed.
const it = range(0, 5)[Symbol.iterator]();
console.log(it.next()) // { value: 0, done: false }
console.log(it.next()) // { value: 1, done: false }
Top comments (0)