Last active
December 23, 2015 23:10
-
-
Save StevenACoffman/dea44b7af45a363a345b to your computer and use it in GitHub Desktop.
Generate an array in a particular range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const start = 5; | |
const end = 20; | |
let myArray = Array.from(new Array(end - start)).map((_, index) => start + index); | |
console.log(myArray); // -> 5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 | |
//alernative | |
myArray = [...(new Array(end - start))].map((_, index) => start + index); | |
console.log(myArray); // -> 5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 | |
//alternative: arrayFrom takes optional map function parameter to avoid intermediate creation | |
myArray = Array.from(new Array(end - start),((_, index) => start + index)); // -> 5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 | |
function range(start=0, stop=0, step = 1) { | |
if (!stop) { | |
stop = start || 0; | |
start = 0; | |
} | |
var length = Math.max(Math.ceil((stop - start) / step), 0) | |
return Array.from({length}, (x, i) => (i * step) + start); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment