Skip to content

Instantly share code, notes, and snippets.

@Soraph
Last active September 11, 2017 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Soraph/c0d57a9732a5edba4d36137806dbe349 to your computer and use it in GitHub Desktop.
Save Soraph/c0d57a9732a5edba4d36137806dbe349 to your computer and use it in GitHub Desktop.
Range function for JavaScript
const sRange = (from, to, includeUpperLimit = false) => {
/*
* Params:
*
* from: integer, first value of cycle and the Array
* to: integer, last value of the cycle
* includeUpperLimit: boolean, if true will use to as last
* element of the Array
*
* Works like Python's range() but two params are mandatory.
* Return an array of values with length = to - from, where
* each element is: index + from.
* es:
* sRange(10, 15);
* result: [10, 11, 12, 13, 14]
*
* sRange(10, 15, true);
* result: [10, 11, 12, 13, 14, 15]
*/
const include = includeUpperLimit ? 1 : 0;
const limit = parseInt(to) - parseInt(from) + include;
const result = Array.apply(null, Array(limit)).map((_, i) => { return i + from; });
return result;
}
export default sRange;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment