Skip to content

Instantly share code, notes, and snippets.

Created August 20, 2015 15:53
Show Gist options
  • Save anonymous/23d7479e1a81cd78b695 to your computer and use it in GitHub Desktop.
Save anonymous/23d7479e1a81cd78b695 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Aug 20, 2015.
    35 changes: 35 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    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) );