O'Reilly logo

Functional JavaScript by Michael Fogus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

function dispatch(/* funs */) {
  var funs = _.toArray(arguments);
  var size = funs.length;

  return function(target /*, args */) {
    var ret = undefined;
    var args = _.rest(arguments);

    for (var funIndex = 0; funIndex < size; funIndex++) {
      var fun = funs[funIndex];
      ret = fun.apply(fun, construct(target, args));

      if (existy(ret)) return ret;
    }

    return ret;
  };
}

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required