Skip to content

Instantly share code, notes, and snippets.

@BrianSipple
Last active March 22, 2018 18:22
Show Gist options
  • Save BrianSipple/3d6303bcfa44584e2bf06cfd1f01d464 to your computer and use it in GitHub Desktop.
Save BrianSipple/3d6303bcfa44584e2bf06cfd1f01d464 to your computer and use it in GitHub Desktop.
JavaScript "range" helper: Generates an iterable list of numbers from `start` to `end`, inclusive.
export default function range(_start, _end) {
// If only one argument (n) is passed, we generate a range from 0 to n.
const start = typeof _end === 'undefined' ? 0 : _start;
const end = typeof _end === 'undefined' ? _start : _end;
// "direction" multiplier to produce a decreasing sequence if `start` is greater than `end`.
const direction = start > end ? -1 : 1;
const size = Math.abs(end - start) + 1;
return Array.from({ length: size }, (_, idx) => start + (idx * direction));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment