Created
August 20, 2015 15:53
-
-
Save anonymous/23d7479e1a81cd78b695 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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