Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating an array with itself

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']
like image 341
ichigolas Avatar asked Dec 27 '22 09:12

ichigolas


2 Answers

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)
like image 80
SLaks Avatar answered Dec 29 '22 01:12

SLaks


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.

like image 28
Cerbrus Avatar answered Dec 29 '22 00:12

Cerbrus