functional way to iterate over range (ES6/7) [duplicate]
Solution 1:
One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:
Array(8).fill(0).map((_, i) => i * i);
Solution 2:
ES7 Proposal
Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method
You can always use something like:
[for (i of Array(7).keys()) i*i];
Running this code on Firefox:
[ 0, 1, 4, 9, 16, 25, 36 ]
This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.
This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:
var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]
Then you can do:
[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25
ES6
A nice way to do this any of:
[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);
This will output:
[ 0, 1, 4, 9, 16, 25, 36 ]