Forked from davidmarkclements/gist:f33ca640cffb8a91129a
Last active
August 29, 2015 14:05
-
-
Save davidmarkclements/bd8e84df62e55dd9cf95 to your computer and use it in GitHub Desktop.
seneca.cmds with $ master - proof of concept
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
//usage: | |
cmds({ | |
$: {general: 'pattern'}, | |
a: {specificying:'pattern'} | |
}) | |
.$a(function (err, args) { | |
console.log(args, Object.keys(args)) | |
}) | |
//after 1.5 secs logs Object {specificying: "pattern", general: "pattern"} ["specificying", "general"] | |
//concept: | |
function cmds(patterns) { | |
patterns = arguments.length > 1 ? arguments : patterns; | |
var api = {}; | |
var master = patterns.$; | |
delete patterns.$; | |
setTimeout(function () { | |
Object.keys(api).forEach(function (k) { | |
api[k]._resolve(null, patterns[k.substr(1)]) | |
}) | |
}, 1500) | |
return Object.keys(patterns).reduce(function (o, k) { | |
if (master) { | |
patterns[k] = defaults(patterns[k], master); | |
} | |
o['$'+k] = makeCb(o); | |
return o; | |
}, api); | |
} | |
function makeCb(api) { | |
function caller(cb) { | |
if (caller._resolved) { | |
cb(caller._err, caller._args); | |
return api; | |
} | |
caller._resolve = function (err, args) { | |
resolve(err, args); | |
cb(err, args); | |
} | |
return api; | |
} | |
function resolve (err, args) { | |
caller._err = err; caller._args = args; | |
caller._resolved = true; | |
} | |
caller._resolve = resolve; | |
return caller; | |
} | |
function defaults(object, source, guard) { | |
var objectTypes = { | |
'boolean': false, | |
'function': true, | |
'object': true, | |
'number': false, | |
'string': false, | |
'undefined': false | |
}; | |
var keys = Object.keys; | |
var index, iterable = object, result = iterable; | |
if (!iterable) return result; | |
var args = arguments, | |
argsIndex = 0, | |
argsLength = typeof guard == 'number' ? 2 : args.length; | |
while (++argsIndex < argsLength) { | |
iterable = args[argsIndex]; | |
if (iterable && objectTypes[typeof iterable]) { | |
var ownIndex = -1, | |
ownProps = objectTypes[typeof iterable] && keys(iterable), | |
length = ownProps ? ownProps.length : 0; | |
while (++ownIndex < length) { | |
index = ownProps[ownIndex]; | |
if (typeof result[index] == 'undefined') result[index] = iterable[index]; | |
} | |
} | |
} | |
return result | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment