January 2011
Intermediate to advanced
224 pages
5h 43m
English
Before moving on to the next chapter, I would like to show you a few more functional techniques that can, once you’ve gotten used to them, make your programs more succinct.
When using higher-order functions, it is often annoying that operators are not
functions in JavaScript. For example, we had to define the add function
earlier in this chapter. Writing these out every time we need them is a pain. One way to
get around that is to create an object like this:
var op = {
"+": function(a, b){return a + b;},
"==": function(a, b){return a == b;},
"===": function(a, b){return a === b;},
"!": function(a){return !a;}
/* and so on */
};So, we can write reduce(op["+"], 0, [1, 2, 3, 4, 5]) to sum an
array.