Preserving arity in function wrappers

Rick Waldron waldron.rick at gmail.com
Sat Sep 14 14:16:28 PDT 2013


On Sat, Sep 14, 2013 at 4:49 PM, Bruno Jouhier <bjouhier at gmail.com> wrote:

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

They won't be writable, but they will be configurable:
https://github.com/rwaldron/tc39-notes/blob/master/es6/2013-07/july-25.md#consensusresolution-3,
which meets the need you've described.

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


More information about the es-discuss mailing list