Skip to content

Instantly share code, notes, and snippets.

@jannesaranpaa
Created August 1, 2016 11:57
Show Gist options
  • Save jannesaranpaa/5b97130f21d8c4dacb9111d2a41da7ea to your computer and use it in GitHub Desktop.
Save jannesaranpaa/5b97130f21d8c4dacb9111d2a41da7ea to your computer and use it in GitHub Desktop.
JavaScript [ES6] implementation of pythons' range()
function* range(start, stop, step = 1)
{
if (stop <= start & step > 0 | stop >= start & step < 0)
{
throw "Stop value is out of range";
}
else if (start >= stop & step > 0 | start <= stop & step < 0)
{
throw "Start value is out of range";
}
else
{
for (let i = start; i < stop & step > 0 | i > stop & step < 0; i += step)
{
yield(i);
}
}
}
for (let i of range(20, 0, -2))
{
console.log(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment