Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.