MapReduce in JavaScript
- // MapReduce.js
- // Name: map
- // Purpose: Perform a given operation on every element in an array.
- // Args:
- // func - the function that implements the desired behaviour for any given array element
- // arr - the array containing the elements to be processed
- function map(func, arr)
- {
- for (i = 0; i < arr.length; i++)
- {
- func(arr[i]);
- }
- }
- // Name: reduce
- // Purpose: Combine all the elements in an array into a single value using a given operation.
- // Args:
- // func - the function that implements the desired behaviour for combining array elements
- // arr - the array containing the elements to be processed
- function reduce(func, arr, initVal)
- {
- var s = initVal; // This will determine the type of s at runtime
- for (i = 0; i < arr.length; i++)
- {
- s = func(s, arr[i]);
- }
- return s;
- }
Comments