Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smartest way to initialize an array in CoffeeScript

What is the best way to initialize an array with a particular value 0 in coffee script. What I have done so far -

[0..100].map -> 0

And

arr = []
arr.push(0) while arr.length isnt 100

If personally feel that the first one will have a poor performance and the second one is too verbose and destroys the charm of programming in coffee script.

Update 2: Incase performance is not an issue then this is also an option I suppose.

arr = new Array(10).join(0).split('')

Update 2: the above will perform better than others options if the join is passed number

Update 3: After seeing a couple of JSPerf tests mentioned in the comments and answers I tried to perform them my self using node.js. Here are the weird results - Code -

    size = 10000000;
key = 1

console.time('splits')
arr1= Array(size + 1).join(key).split('')
console.timeEnd('splits')


console.time('maps')
arr2 = [1..size].map -> key
console.timeEnd('maps')

console.time('loop')
arr3 = []
arr3.push(key) while arr3.length isnt size
console.timeEnd('loop')


console.time('for')
arr4 = (0 for n in [0...size])
console.timeEnd('for')

console.time('for-no-var')
arr5 = (0 for [0...size])
console.timeEnd('for-no-var')


### node- 0.10.15
splits: 162ms
maps: 1639ms
loop: 607ms
for: 659ms
###

Interestingly the split and join is taking much less time. Also if we care about performance really then we should try to initialize and array which is really big instead of something in the order of hundreds.

like image 780
tusharmath Avatar asked Aug 30 '13 22:08

tusharmath


People also ask

What is the proper way to declare an array?

We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};

Should you use CoffeeScript?

CoffeeScript is something that makes even good JavaScript code better. CoffeeScript compiled code can do everything that natively written JavaScript code can, only the code produced by using CoffeeScript is way shorter, and much easier to read.


2 Answers

There's also the arr = (0 for [1..100]) form if you don't want to have any iteration variable leaking outside the comprehension ;)

like image 161
epidemian Avatar answered Oct 07 '22 17:10

epidemian


My vote goes to arr = (0 for x in [0...100])

It's clear, concise, CoffeeScript-ish, and compiles to reasonably clear Javascript:

var arr, x;

arr = (function() {
  var _i, _results;
  _results = [];
  for (x = _i = 0; _i < 100; x = ++_i) {
    _results.push(0);
  }
  return _results;
})();
like image 28
nicolaskruchten Avatar answered Oct 07 '22 18:10

nicolaskruchten