Skip to content

Instantly share code, notes, and snippets.

@j2labs
Forked from gtzilla/gist:1247115
Created September 28, 2011 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j2labs/1247166 to your computer and use it in GitHub Desktop.
Save j2labs/1247166 to your computer and use it in GitHub Desktop.
arity binding decorator for javascript
function arity_decorator(fun) {
function wrapped() {
if(arguments.length != fun.length)
throw new Error("Y U NO USE RIGHT?!")
fun.apply(this, arguments);
}
return wrapped;
}
function foo(x, y) {
console.log('X:' + x);
console.log('Y:' + y);
}
foo = arity_decorator(foo);
/*
* This is what it looks like to use it. Notice an error is thrown when the
* wrong Arity is used.
*/
> function arity_decorator(fun) {
... function wrapped() {
... if(arguments.length != fun.length)
... throw new Error("Y U NO USE RIGHT?!")
... fun.apply(this, arguments);
... }
... return wrapped;
... }
>
>
> function foo(x, y) {
... console.log('X:' + x);
... console.log('Y:' + y);
... }
>
>
> foo = arity_decorator(foo);
[Function: wrapped]
>
> foo()
Error: Y U NO USE RIGHT?!
at wrapped ([object Context]:4:7)
at [object Context]:1:1
at Interface.<anonymous> (repl.js:171:22)
at Interface.emit (events.js:64:17)
at Interface._onLine (readline.js:153:10)
at Interface._line (readline.js:408:8)
at Interface._ttyWrite (readline.js:585:14)
at ReadStream.<anonymous> (readline.js:73:12)
at ReadStream.emit (events.js:81:20)
at ReadStream._emitKey (tty_posix.js:307:10)
> foo(3,4)
X:3
Y:4
> foo(3,4,5)
Error: Y U NO USE RIGHT?!
at wrapped ([object Context]:4:7)
at [object Context]:1:1
at Interface.<anonymous> (repl.js:171:22)
at Interface.emit (events.js:64:17)
at Interface._onLine (readline.js:153:10)
at Interface._line (readline.js:408:8)
at Interface._ttyWrite (readline.js:585:14)
at ReadStream.<anonymous> (readline.js:73:12)
at ReadStream.emit (events.js:81:20)
at ReadStream._emitKey (tty_posix.js:307:10)
>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment