Created
July 12, 2012 17:05
-
-
Save gordonbrander/3099349 to your computer and use it in GitHub Desktop.
toMethod and toLambda - higher order helpers for codebases that use both functional and OOP styles
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
// Convert a function that does not use `this` context into a function that | |
// does. The category of information that was previously passed as the first | |
// parameter of the function is now its `this` context. | |
function toMethod(lambda) { | |
return function () { | |
var args = [this]; | |
var concat = args.concat; | |
// Spread arguments over arity of concat, since arguments is not a true array. | |
var combined = concat.apply(args, arguments); | |
return lambda.apply(null, combined); | |
}; | |
} | |
// Convert a method func that uses a `this` context into a function that takes | |
// the context object as the first parameter. | |
function toLambda(method) { | |
return function (context) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
return method.apply(context, args); | |
}; | |
} |
I like the use of the term "lambda" in your example to distinguish between methods and traditional functions. Maybe toLambda
and toMethod
are better names?
Update: changed the name to Lambda.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We actually use on of this functions in SDK :)
https://github.com/mozilla/addon-sdk/blob/master/packages/api-utils/lib/functional.js#L18-23