Skip to content

Instantly share code, notes, and snippets.

@sirlancelot
Forked from anonymous/zzz.js
Last active April 21, 2017 21:47
Show Gist options
  • Save sirlancelot/e1d2ba6c8e07cbf61bd1 to your computer and use it in GitHub Desktop.
Save sirlancelot/e1d2ba6c8e07cbf61bd1 to your computer and use it in GitHub Desktop.
An experiment to create named parameters in Javascript.
var createNamedParameters = require("./named-parameters")

var fn = createNamedParameters(["greeting", "person"], function(a, b) {
	console.log(a, b)
})

fn.greeting("hello") // set a
fn.person("world")   // set b
fn() // console.log gets run

// append additional parameters which were unnamed.
var extraParams = createNamedParameters(["world"], function(a, extra) {
	console.log(a, extra)
})

extraParams.world("first param") // set a
extraParams("extra param") // console.log gets run.
(function(global, factory) {
// Defines a module that works in Node.js & Browsers
var mock, local = (typeof module === "object" && module.exports) ? module :
(mock = { exports: {} })
factory(local, local.exports)
if (local === mock) global["createNamedParameters"] = local.exports
}(this, function(module, exports) {
module.exports = function createNamedParameters(argv, fn) {
var i = 0
var length = argv.length
var composed = Array(length)
function composing() {
var i = 0, len = arguments.length
composed.length = length + len
for (; i < len; i++) composed[i] = arguments[i]
try {
return fn.apply(this, composed)
} finally {
composed = Array(length)
}
}
for (; i < length; i++) addNamedParam(composing, composed, argv[i], i)
return composing
}
// Check that we're not going to override a property of a function.
function addNamedParam(fn, args, name, pos) {
if (!name || name in fn)
throw new ReferenceError("Can't use `" + name + "` as named parameter.")
fn[name] = function curryParam(v) {
args[pos] = v
return fn
}
}
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment