Kai
Kai

Reputation: 2073

Is it possible to make this code shorter?

I have javascript code:

var newPositions = new Array(count);
                for (var i = 0; i < count; i++) {
                    newPositions[i] = i;
                }

Is it possible to init this array from 0 to count more quickly(in one-line I mean)?
upd: count is a number that may differ in execution time

upd2: dont think about algorithm, only way to write this code in one-line. As @Martin Jespersen suggest and using somebody deleted answer:

for (var i = 0, newPositions = []; i < count; newPositions[i] = i++) 

Upvotes: 2

Views: 167

Answers (6)

Anthony Grist
Anthony Grist

Reputation: 38345

That's about as 'easy' as it gets to do what you want; the only potential optimisation is to turn the array initialisation into a function, like so:

function range(count) {
    var countArray = new Array(count);
    for(var i = 0; i < count; i++) {
        countArray[i] = i;
    }
    return countArray;
}

Then assign it to your variable:

var newPositions = range(count);

Only an optimisation if you needed to do that a reasonable number of times, to account for the additional time spent coding the function. If it's being done once then it's about as good as it's going to get.

As a sort of aside, the code you have initialises newPositions from 0 to count-1, rather than 0 to count, due to the way your for loop is set up. Change i < count to i <= count in your for loop if you want to include the value of count in your array.

Upvotes: 1

Martin Jespersen
Martin Jespersen

Reputation: 26183

for (var i = 0,newPositions=[]; i < count; i++) {
  newPositions[i] = i;
}

Upvotes: 4

David M&#229;rtensson
David M&#229;rtensson

Reputation: 7600

Not much easier i'm afraid unless you alwasy use the same count as in Jamiec's answer.

var newPositions = [];
while(count-- > 0)
     newPositions[count] = count;

This is a little shorter but the same code except it changes cout so maybe use a temp var fpor that instead.

Upvotes: 0

Sparafusile
Sparafusile

Reputation: 4956

The smart-ass answer would be:

for (var i = 0; i < count; i++) newPositions[i] = i;

But a better answer (or question) would be: Why is this array useful to you at all? The array is holding values that can be easily calculated on the fly. With more information we can give you a better answer.

Upvotes: 0

Jamiec
Jamiec

Reputation: 136094

If count is always a known number, then the syntax for creating a javascript array in 1 line is

var myArray = [0,1,2,3,4,5,6,7]; //assuming count was 8

Upvotes: 0

Timothy Khouri
Timothy Khouri

Reputation: 31845

No, there is not a way to optimize that any more :)

Upvotes: 1

Related Questions