I'm trying to implement Array.repeat
, so
[3].repeat(4) // yields
=> [3, 3, 3, 3]
... and is driving me crazy.
Tried with this:
Array::repeat = (num)->
array = new Array
for n in [0..num]
array.concat(this)
array
But [3].repeat(x)
always returns []
. Where I'm screwing it up? Or is there a better approach do this?
Final result:
Array::repeat = (num)->
array = new Array
return array if num < 1
for n in [1..num]
array = array.concat(this)
array
['a'].repeat(5)
=> ['a', 'a', 'a', 'a', 'a']
array.concat
returns a new array and does not modify the existing one.
You need to write
array = array.concat(dup)
Alternatively, you can use push()
, which does modify the original array:
array.push.apply(array, dup)
This is rather simple:
function repeat(array, n){
var out = [];
for(var i = 0; i < n; i++) {
out = out.concat(array);
}
return out;
}
Or prototyping:
Array.prototype.repeat = function(n){
var out = [];
for(var i = 0; i < n; i++) {
out = out.concat(this);
}
return out;
}
That's native JS, not sure how you'd do that in CoffeeScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With