Skip to content

Instantly share code, notes, and snippets.

@matthewstokeley
Last active November 7, 2019 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewstokeley/f9e34c38521e5add25b559e87767a97d to your computer and use it in GitHub Desktop.
Save matthewstokeley/f9e34c38521e5add25b559e87767a97d to your computer and use it in GitHub Desktop.
annotating the '_.invoke' method from underscore.js

Underscore's invoke method

/*
 *  @version 0.0.1
 */
// Invoke a method (with arguments) on every item in a collection.
 _.invoke = restArguments(function(obj, path, args) {

An alias is declared, and the restArguments function is given a first-order function.

    var contextPath, func;
    if (_.isFunction(path)) {
      func = path;
    } else if (_.isArray(path)) {
      contextPath = path.slice(0, -1);
      path = path[path.length - 1];
    }
    
    return _.map(obj, function(context) {
      var method = func;
      if (!method) {
        if (contextPath && contextPath.length) {
          context = deepGet(context, contextPath);
        }
        if (context == null) return void 0;
        method = context[path];
      }
      return method == null ? method : method.apply(context, args);
    });
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment