What would be the tersest way to create this array:
var x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
For example, a for
loop:
var x = [];
for (var i=1;i<=20;i++) {
x.push(i);
}
Or a while
loop:
var x = [], i = 1, endInt = 20;
while (i <= endInt) {
x.push(i);
i++;
}
Would there be other examples that would be terser -- in other words -- less code? I'm thinking of things like in Ruby where the equivalent code I believe would be as simple as 1..20
. I'm not aware of syntax like that in JavaScript but I'm wondering if there are shorter ways to do that same thing.
UPDATE: I wasn't thinking of removing semicolons or var
for answers in the question, but I have to admit the question implies that. I am more curious about algorithms than shaving bytes. Sorry if I was unclear! Also, making it into a function is simple enough, just slap function range(start, end) { /* guts here */ }
around it and you're there. The question is are there novel approaches to the "guts."
JSFiddle
It can be done with features from the ES6, currently only supported by Firefox thou. I found a compatibility table here: http://kangax.github.io/compat-table/es6/
If you want to have some other range then I guess you could do
Which would then be [5,6,7,8,9]
while-- is the way to go
returns [1,2,3,4,5,6,7,8,9,10]
explained with start & length
returns [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
want range?
explained with start & end
returns [25, 26, 27, 28, 29, 30]
for --
for++
WHY is this theway to go?
while -- is prolly the fastest loop;
direct setting is faster than push & concat;
[] is also faster than new Array(10);
it's not much longer code than all the others
byte saving techniques:
so if u want a function for this
with start,end (range)
so now range(3,7) returns [3,4,5,6,7]
u save bytes in many ways here and this function is also very fast as it does not use concat, push, new Array and it's made with a while --
If you are looking to shave characters off anyway possible without regard for readability, this is the best I can do:
Not a lot better than yours though.
Edit:
Actually this works better and shaves off a couple characters:
Edit 2:
And here's my entry for a general "range" function in the least number of characters:
Again, don't write code this way. :)
In my knowledge, the option of using for loop, as you mentioned, is the most tersest.
That is,
Using ES6
numArr = Array(5).fill(0).reduce(arr=>{ arr.push(arr.length); return arr },[])