Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Created July 12, 2012 17:05
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 gordonbrander/3099349 to your computer and use it in GitHub Desktop.
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
// 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);
};
}
@gordonbrander
Copy link
Author

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