Chapter 5. Function-Building Functions
This chapter builds on the idea of first-class functions by explaining how and why one builds functions on the fly. It explores various ways to facilitate function “composition”—snapping together functions like Lego blocks to build richer functionality from parts.
The Essence of Functional Composition
Recall that the function invoker
from Chapter 4 built a function taking an object as its
first argument and attempted to call a method on it. If you’ll recall,
invoker returned undefined if the method was not available on the
target object. This can be used as a way to compose multiple invokers
together to form polymorphic functions, or functions that exhibit
different behaviors based on their argument(s). To do this, I’ll need a
way to take one or more functions and keep trying to invoke each in turn,
until a non-undefined value is returned. This function, dispatch, is defined imperatively as
follows:
functiondispatch(/* funs */){varfuns=_.toArray(arguments);varsize=funs.length;returnfunction(target/*, args */){varret=undefined;varargs=_.rest(arguments);for(varfunIndex=0;funIndex<size;funIndex++){varfun=funs[funIndex];ret=fun.apply(fun,construct(target,args));if(existy(ret))returnret;}returnret;};}
This is a lot of code to perform a simple task.[51]
To be clear, what you want to do is return a function that loops through an array of functions, calls each with an object, and returns the first actual ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access