Skip to content

Instantly share code, notes, and snippets.

@73nko
Created July 3, 2018 05:42
Show Gist options
  • Save 73nko/bb083c14ce9c43ce09fdf39a598555e4 to your computer and use it in GitHub Desktop.
Save 73nko/bb083c14ce9c43ce09fdf39a598555e4 to your computer and use it in GitHub Desktop.
Creates an array with the span of numbers
/**
* Creates an array with the span of numbers going from `first` and ending at
* `last` if possible depending on the specified step value.
* @param {number} first
* First number that should appear in the returned array.
* @param {number} last
* Last number that should appear in the returned array.
* @param {number=} opt_step
* Defaults to `1` if not given or if `0` or `NaN` is specified. The
* difference between each subsequent number in the returned array.
* @returns {Array}
* An array containing the sequence of numbers starting at `first` and ending
* at `last`. If `first` is less than `last` and `opt_step` is less than `0`
* or if `last` is less than `first` and `opt_step` is greater than `0` an
* empty array will be returned. If `opt_mapper` is given the array will
* contain the sequence of mapped.
*/
function span(first, last, opt_step, opt_mapper) {
opt_step = +opt_step || 1;
let result = [];
for (let mult = opt_step < 0 ? -1 : 1; mult * (last - first) >= 0; first += opt_step) {
result.push(first);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment