MapReduce in JavaScript

  1. // MapReduce.js  
  2. // Name:  map  
  3. // Purpose:  Perform a given operation on every element in an array.  
  4. // Args:  
  5. //   func - the function that implements the desired behaviour for any given array element  
  6. //   arr  - the array containing the elements to be processed  
  7. function map(func, arr)  
  8. {  
  9.   for (i = 0; i < arr.length; i++)  
  10.   {  
  11.     func(arr[i]);  
  12.   }  
  13. }  
  14.   
  15. // Name:  reduce  
  16. // Purpose:  Combine all the elements in an array into a single value using a given operation.  
  17. // Args:  
  18. //   func - the function that implements the desired behaviour for combining array elements  
  19. //   arr  - the array containing the elements to be processed  
  20. function reduce(func, arr, initVal)  
  21. {  
  22.   var s = initVal; // This will determine the type of s at runtime  
  23.   for (i = 0; i < arr.length; i++)  
  24.   {  
  25.     s = func(s, arr[i]);  
  26.   }  
  27.   return s;  
  28. }  

Comments

Popular Posts