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.
arr = (0 for n in [0...100])pushout performsary[x]=0on Chrome, but not on Firefox. There are many more such tests on jsperf.com['0','0',...]. Initials to characters, not integers.