Created
October 30, 2013 15:33
-
-
Save hanbzu/7234645 to your computer and use it in GitHub Desktop.
JavaScript: Reduce, an example. Thanks to Christian Johansen.
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
| // 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