-
-
Save qgustavor/3f958530b8e542a70cf6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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); | |
} | |
} |
This file contains hidden or 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
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