Concatenating an array with itself

I am trying to implement Array.repeat

, so

[3].repeat(4) // yields
=> [3, 3, 3, 3]

      

... and drives me crazy.

Tried with this:

Array::repeat = (num)->
  array = new Array
  for n in [0..num]
    array.concat(this)
  array

      

But it [3].repeat(x)

always returns []

. Where do I bring this? Or is it better to do it?

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']

      

+3


source to share


3 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 modifies the original array:

array.push.apply(array, dup)

      

+5


source


It's pretty 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;
}

      

This native JS, not sure how you would do it in CoffeeScript.

+1


source


I think this is what the function looks like:

Array.prototype.repeat = function(count) {
    if(count==null||1*count!=count)  //check for cerrect count
        return this.valueOf(); 
    var length = this.length;     //Length
    var return = this.valueOf();  //0 repats equals in the same array
    for(var i=0; i<count; i++) {  //Repeating the count
      for(var j=0; j<length; j++) {
        return.push(this[j]);
      }
    }
}

      

0


source







All Articles