Skip to content

Instantly share code, notes, and snippets.

@sarahbkim
Last active January 25, 2016 02:01
Show Gist options
  • Save sarahbkim/767b2cc76a9e6f7f0f8d to your computer and use it in GitHub Desktop.
Save sarahbkim/767b2cc76a9e6f7f0f8d to your computer and use it in GitHub Desktop.
reduce
// custom implementation of reduce fn just for fun
Array.prototype.myReduce = function(fn, customStart) {
var result = customStart ? customStart : null;
for(var i=0;i<this.length;i++) {
result = fn(result, this[i])
}
return result
};
// get hash of unique word to frequency
['hi', 'cat', 'bye', 'bye', 'cat', 'h'].reduce(function(prev, curr) {
prev[curr] = prev[curr] ? prev[curr] += 1 : 1
return prev
}, {});
// custom Fn should return the same results
['hi', 'cat', 'bye', 'bye', 'cat', 'h'].myReduce(function(prev, curr) {
prev[curr] = prev[curr] ? prev[curr] += 1 : 1
return prev
}, {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment