Hey, thanks for sharing this @guyariely
very timely, as I was just looking at JavaScript range and generator functions 🙂
One question I have is what is the advantage of using an iterator here, rather than a simple for n to n and returning and array?
I found this article (joshwcomeau.com/snippets/javascrip...) which uses a for n to generate the output, and seems to work just as well, and also, like @lukeshir mentioned, supports forEach because the return is an array.
const range = (start, end, step = 1) => {
let output = [];
if (typeof end === 'undefined') {
end = start;
start = 0;
}
for (let i = start; i < end; i += step) {
output.push(i);
}
return output;
};
Hey Daniel, The reason I used iterators was to match Python range structure.
Notice how in order to get the python list (or Array in JavaScript), you have to call list(). The same kind of structure and semantics can be achieved in JavaScript by using iterators.
I agree this isn't the greatest use case for iterators, but it's simple and opens up the door for further exploration of this great tool.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hey, thanks for sharing this @guyariely very timely, as I was just looking at JavaScript
range
and generator functions 🙂One question I have is what is the advantage of using an iterator here, rather than a simple
for n to n
and returning and array?I found this article (joshwcomeau.com/snippets/javascrip...) which uses a
for n
to generate the output, and seems to work just as well, and also, like @lukeshir mentioned, supportsforEach
because the return is an array.Link to a sandbox comparison: codesandbox.io/s/range-4idy5?file=...
Anyhow, thanks again for sharing!
Hey Daniel, The reason I used iterators was to match Python range structure.
Notice how in order to get the python list (or Array in JavaScript), you have to call list(). The same kind of structure and semantics can be achieved in JavaScript by using iterators.
I agree this isn't the greatest use case for iterators, but it's simple and opens up the door for further exploration of this great tool.