Preserving arity in function wrappers

Bruno Jouhier bjouhier at gmail.com
Sat Sep 14 13:49:52 PDT 2013


The classical pattern for function wrappers is the following

function wrap(fn) {
  return function F() { ... var result = fn.apply(this, arguments); ...
return result; };
}

This pattern has one problem though: the returned function has a different
arity than the original function. This causes problems with libraries that
test fn.length; for example with express and moccha in node.js.

I found two ways to restore the arity:
* inside wrap, call F.toString(), replace F() by F(a1, a2, ...), eval and
return the new function.
* dynamically create one variant of the wrap function for each arity.
Similar but the substitution and eval is done on wrap rather than on F. A
bit more complex to set up but more efficient.

I find it rather clumsy to have to call eval to solve this. Maybe there is
a better solution without eval but if there isn't it may be interesting to
improve the language for this. Some ideas (probably naive):

* make the length property of functions writable.
* enhance the Function(arg1, arg1, ..., functionBody) constructor to accept
a function as functionBody, or introduce a Function(nArgs, bodyFn) variant.

WDYT?

Bruno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130914/c91dfe23/attachment.html>


More information about the es-discuss mailing list