Skip to content

Instantly share code, notes, and snippets.

@mpj
Forked from anonymous/gist:23d7479e1a81cd78b695
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpj/45927f139d544123093d to your computer and use it in GitHub Desktop.
Save mpj/45927f139d544123093d to your computer and use it in GitHub Desktop.
function reduce(arr, fn, initial) {
//there's no more elements in the array, we return I get that
if (arr.length === 0) {
return initial;
} // base case, does not recurse
// we are calling the actual function here with the first element in the array
//I don't get what initial is ??
initial = fn(initial, arr[0]); // sets init-OP-first result as new init
//calling slice chops the head and passes the rest to reduce again.
return reduce(arr.slice(1), fn, initial);
}
function sum(prev,next,index,arr) {
return prev + next;
}
function countWords(countMap, word) {
countMap[word] = ++countMap[word] || 1 ;// increment or initialize to 1
console.log(countMap[word]);
return countMap;
}
var arr = [1,2,3,4];
//sum the numbers in the array
var total = reduce(arr,sum,0);
console.log("total="+total);
//count the number of words in a array
var arr1 = [ 'quis', 'velit', 'voluptate', 'nostrud', 'aute', 'ea', 'nostrud', 'occaecat', 'tempor', 'eu', 'ut', 'occaecat', 'labore', 'occaecat', 'aliqua', 'culpa', 'incididunt', 'ex' ];
var tempArr = reduce(arr1,countWords,{});
console.log("tempArr="+JSON.stringify(tempArr) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment