Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Created October 30, 2013 15:33
Show Gist options
  • Select an option

  • Save hanbzu/7234645 to your computer and use it in GitHub Desktop.

Select an option

Save hanbzu/7234645 to your computer and use it in GitHub Desktop.
JavaScript: Reduce, an example. Thanks to Christian Johansen.
// We want to compute the total length of a buffer
var totalLength = 0;
for (var i = 0; i < buffers.length; i++) {
totalLength += buffers[i].length;
}
// We can do this with map-reduce
var totalLength = buffers.
map(function (chunk) { return chunk.length; }).
reduce(function (prev, curr) { return prev + curr; }, 0);
// But we're using this simple operation
function add(a, b) {
return a + b;
}
// Why not use it and our own 'prop' function?
// ...this one-liner is much more readable!
var totalLength = buffers.map(prop("length")).reduce(add);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment