inject :: Enumerable

inject(accumulator, iterator) -> accumulatedValue

 

Incrementally builds a result value based on the successive results of the iterator. This can be used for array construction, numerical sums/averages, etc.

 

Examples

 

$R(1,10).inject(0function(acc, n) { return acc + n; })

// -> 55 (sum of 1 to 10)

 

$R(2,5).inject(1function(acc, n) { return acc * n; })

// -> 120 (factorial 5)

 

['hello''world''this''is''nice'].inject([], function(array, value, index) {

  if (0 == index % 2)

    array.push(value);

  return array;

})

// -> ['hello', 'this', 'nice']

 

Note how we can use references (see next section):

 

var array1 = [];

var array2 = [123].inject(array1, function(array, value) {

  array.push(value * value);

  return array;

});

array2

// -> [1, 4, 9]

array1

// -> [1, 4, 9]

array2.push(16);

array1

// -> [1, 4, 9, 16]

 

Performance considerations

 

When injecting on arrays, you can leverage JavaScript’s reference-based scheme to avoid creating ever-larger cloned arrays (as opposed to JavaScript’s native concat method, which returns a new array, guaranteed).

 

 


Prototype API 1.5.0 - prototypejs.org