inject
inject(accumulator, iterator[, context]) -> 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.
The optional context
parameter is what the iterator function will be bound to. If used, the this
keyword inside the iterator will point to the object given by the argument.
Examples
$R(1,10).inject(0, function(acc, n) { return acc + n; })
// -> 55 (sum of 1 to 10)
$R(2,5).inject(1, function(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 = [1, 2, 3].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).