Function length
David Herman
dherman at mozilla.com
Fri Jun 15 12:06:06 PDT 2012
Here are my thoughts.
- Despite the fact that `arguments` and lack of arity-checking makes it unreliable, JS exposes .length and it's supposed to mean the number of "normal" or "expected" arguments. This suggests it should not include defaulted arguments, and should not include rest-arguments.
- ES6 makes it unnecessary to use `arguments` since defaults and rest-args can do everything it can do but in more convenient ways.
- This suggests that .length *could* become a more reliable source of information if people move away from using `arguments`.
- And yet it's still not the whole story. If you want to introspect a function's arity, you'd really like to know the full range of acceptable arity information. For example, Racket actually provides quite a bit of information about a procedure' arity:
http://bit.ly/McZxQt
- Racket's API is super complex. But I could see at *least* offering a Function.prototype.hasRestArg getter.
Dave
Given that we already expose .length and (despite the fact that I agree it's unreliable) people do seem to use it from time to time,
On Jun 9, 2012, at 6:52 PM, Irakli Gozalishvili wrote:
> I just noticed strange behavior in spider monkey implementation of rest arguments:
>
> (function(a, b, ...rest) {}).length // => 2
>
> I think ignoring `rest` in length is pretty counter intuitive. For example I have small utility function that
> I use to dispatch depending on argument length.
>
> var sum = dispatcher([
> function() { return 0 },
> function(x) { return x },
> function(x, y) { return x + y },
> function(x, y, z) { return Array.prototype.slice.call(arguments, 1).reduce(sum, x) }
> ])
>
> This behavior of rest would obviously break assumptions made by this library. That being said I don't think `3` would be any better. Maybe such functions length should be:
>
> - Infinity ?
> - 2.5 ?
>
> That way libraries would be able to handle them in a nice way:
>
> var sum = dispatcher([
> () => 0,
> (x) => x,
> (x, y) => x + y,
> (x, ...rest) => rest.reduce(sum, x)
> ])
>
>
> Regards
> --
> Irakli Gozalishvili
> Web: http://www.jeditoolkit.com/
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120615/9f6b9151/attachment.html>
More information about the es-discuss
mailing list