Created
August 18, 2014 15:48
-
-
Save davidmarkclements/f33ca640cffb8a91129a to your computer and use it in GitHub Desktop.
seneca.cmds with __proto__ - 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({ | |
__proto__: {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"] | |
//concept: | |
function cmds(patterns) { | |
patterns = arguments.length > 1 ? arguments : patterns; | |
var api = {}; | |
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) { | |
patterns[k] = Object.create(patterns.__proto__, Object.getOwnPropertyDescriptors(patterns[k])) | |
//seneca probably does an object.keys, so instead of object create it would be | |
// patterns[k] = _.defaults(patterns[k], patterns.__proto__); | |
// in which case we lose the value of the proto chain, so we could just call it $$ or something | |
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; | |
} | |
'getOwnPropertyDescriptors' in Object || ( | |
Object.getOwnPropertyDescriptors = function (Object) { | |
var | |
gOPD = Object.getOwnPropertyDescriptor, | |
gOPN = Object.getOwnPropertyNames, | |
gOPS = Object.getOwnPropertySymbols, | |
gNS = gOPS ? function (object) { | |
return gOPN(object).concat(gOPS(object)); | |
} : | |
gOPN, | |
descriptors | |
; | |
function copyFrom(key) { | |
descriptors[key] = gOPD(this, key); | |
} | |
return function getOwnPropertyDescriptors(object) { | |
var result = descriptors = {}; | |
gNS(object).forEach(copyFrom, object); | |
descriptors = null; | |
return result; | |
}; | |
}(Object) | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment