Skip to content

Instantly share code, notes, and snippets.

Created January 27, 2015 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save anonymous/2ed18ff81436ad8ba986 to your computer and use it in GitHub Desktop.
Save anonymous/2ed18ff81436ad8ba986 to your computer and use it in GitHub Desktop.
An experiment to create named parameters in Javascript
var reservedWords = "arguments caller length name prototype __proto__".split(" ")
module.exports = createNamedParameters
function createNamedParameters(argv, fn) {
var length = fn.length
var composed = Array(length)
if (argv.length !== length) throw new Error("Argument lengths don't match")
function composing() {
var len = arguments.length, args = new Array(len)
for (var i = 0; i < len; i++) args[i] = arguments[i]
return applyFn(fn, composed.concat(args), this);
}
for (var i = 0; i < length; i++)
addNamedParam(composing, composed, argv[i], i)
return composing;
}
// Check that we're not modifying the function prototype with a reserved word
function addNamedParam(fn, args, name, pos) {
if (~reservedWords.indexOf(name))
throw new Error("Can't create named parameter with reserved word: " + name)
fn[name] = function curryParam(v) {
args[pos] = v
return fn;
}
}
// Make it fast for common cases
function applyFn(fn, args, ctx) {
switch (args.length) {
case 0: return fn.call(ctx); break;
case 1: return fn.call(ctx, args[0]); break;
case 2: return fn.call(ctx, args[0], args[1]); break;
case 3: return fn.call(ctx, args[0], args[1], args[2]); break;
default: return fn.apply(ctx, args);
}
}
var create = require("./named-parameters")
var fn = create(["greeting", "person"], function(a, b) {
console.log(a, b)
})
fn.greeting("hello").person("world")()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment