Skip to content

fn to return extra arguments #25

Open
@boneskull

Description

@boneskull

I looked through the codebase but didn't see this; sorry if I missed it.

Given the following function, I frequently find myself taking arguments[1..n] and doing something with it:

function foo(bar) {
  // do something with arguments[1..n]
}

So, a function like the following is helpful for me:

function extraArgs(fn, arg_obj) {
  var idx;
  arg_obj = arg_obj || [];
  if (!_.isFunction(fn)) {
    throw new Error('extraArgs() expects a function parameter');
  }
  idx = fn.toString()
    .replace(/^function\s+.*\((.+?)\).+/, '$1')
    .match(/\s*,\s*/)
    .length;
  return _.toArray(arg_obj).slice(idx);
}

Non-trivial example:

function formatError() {
  var message = require('util').format.apply(null, arguments);
  return new Error(message);
}

function httpError(status_code) {
  var e = formatError.apply(null, extraArgs(httpError, arguments));
  e.status_code = status_code;
  return e;
}

function frobulate(widget) {
  if (!_.isArray(widget)) {
    throw httpError(500, 'could not frobulate %s', widget);
  }
  // proceed to frobulate
}

frobulate({});

Would something like this be appropriate for this library? I can provide PR if there's interest.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions