replace function with ruby style block
Armed with underscore, I could achieve something fantastic like below:
_([1,2,3]).chain().map(function(n) {return n*2}).reduce(function(m,a) {return m +a},0).value()
Obviously, the most verbose part is the definition of function
. Could it be more simpler? Something like:
_([1,2,3]).chain().map( {|n| return n*2} ).reduce({|m,a| return m+2; },0).value开发者_如何学C()
If you take delight in writing compact functional programming, check Functional (caveat: it takes the non-OOP approach):
JS> reduce('+', 0, map('*2', [1, 2, 3]))
12
It feels almost like you are writing Haskell ;-)
Haskell> foldl (+) 0 (map (*2) [1, 2, 3])
12
If you were using CoffeeScript you could write
_([1,2,3]).chain().map((n) -> n*2).reduce((m,a) -> m+2, 0).value()
using anonymous functions.
JavaScript doesn't have blocks of course.
精彩评论