-
Notifications
You must be signed in to change notification settings - Fork 71
reduce
reduce
allows for reduction operations on ParallelArrays
that reduce all the elements in the array to a single result -- for instance, computing the sum of all elements of an array.
reduce
is free to group calls to the elemental function in arbitrary ways and order the calls arbitrarily. If the elemental function is associative, then the final result will be the same regardless of the ordering. Addition is an example of an associative operation, and the sum of a ParallelArray
will always be the same, regardless of the order of calls to an elemental function that performs addition. Average is an example of a non-associative operation -- for example, Average(Average(2, 3), 9) is 5 2/3, while Average(2, Average(3, 9)) is 4.
reduce
is permitted to choose whichever call ordering it finds convenient; it is only required to return a result consistent with some call ordering, and is not required to chose the same call ordering on subsequent calls. Furthermore, reduce
does not magically resolve problems related to overflow and the well-documented fact that some floating-point numbers are not represented exactly in JavaScript and the underlying hardware.
reduce
does not require the elemental function to be commutative, since it does induce reordering of the arguments passed to the elemental function.
myParallelArray.reduce(elementalFunction, arg1, arg2, ...)
-
elementalFunction
: described below. -
arg1
,arg2
, ...: optional arguments, passed unchanged toelementalFunction
.
function(a, b, arg1, arg2, ...) { <body> }
-
a
: The partial result of the reduction so far. -
b
: The next element to be processed. -
arg1
,arg2
, ...: The same as the optional arguments passed toreduce
.
The result of the elemental function is a new partial result of reduction, which is typically then used in further applications of the elemental function.
Inside the elemental function, the value of this
will be the ParallelArray
object on which reduce
was invoked. For example, in the invocation of reduce
above, this
would refer to myParallelArray
.
The final result of reduction. If the ParallelArray
has only one element, then that element is returned.
If the source array is empty, reduce
returns undefined
.
// calculate the sum of the elements of a ParallelArray
var source = new ParallelArray([1,2,3,4,5]);
var sum = source.reduce(function plus(a,b) { return a+b; });