Last active
December 11, 2015 18:19
-
-
Save puffnfresh/4640930 to your computer and use it in GitHub Desktop.
Wat? You need arity guard!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function arityGuard(f) { | |
function guarded() { | |
var length = f._length || f.length; | |
if(arguments.length != length) { | |
throw new TypeError( | |
(f._name || f.name || '<anonymous>') + | |
' called with ' + | |
arguments.length + | |
' argument(s), expected ' + | |
length | |
); | |
} | |
return f.apply(this, arguments); | |
} | |
// name and length assignments are ignored in most browsers. | |
// Use special _name and _length properties as fallbacks. | |
guarded._name = guarded.name = f._name || f.name; | |
guarded._length = guarded.length = f._length || f.length; | |
return guarded; | |
} | |
// > function add(a, b, c) { return a + b + c; } | |
// | |
// > arityGuard(add)(1, 2) | |
// TypeError: add called with 2 argument(s), expected 3 | |
// | |
// > arityGuard(add)(1, 2, 3) | |
// 6 | |
// | |
// > arityGuard(add)(1, 2, 3, 4) | |
// TypeError: add called with 4 argument(s), expected 3 | |
// > > [1, 2, 3].map(arityGuard(parseInt)) | |
// TypeError: parseInt called with 3 argument(s), expected 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment