Last active
August 26, 2015 12:51
-
-
Save roblabla/26eb829c6889cfc75582 to your computer and use it in GitHub Desktop.
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
function findArgs(acc, v, k) { | |
if (typeof v === "string" && v[0] === '$') | |
acc.push({ "path": k, "val": v.subst(1) }); | |
else if (Array.isArray(v) || typeof v === "object") | |
acc = acc.concat(_.map(_.reduce(v, findArgs, []), (v) => { "path": k + "." + v.path, "val": v.val })); | |
return acc; | |
} | |
function setField(path, val, into) { | |
var c = path.split('.').reverse(); | |
while (c.length > 1) { | |
into = into[c.pop()]; | |
} | |
into[c.pop()] = val; | |
} | |
function extendType(functions, defaultTypeArgs) { | |
var argPos = _.reduce(defaultTypeArgs, findArgs, []); | |
return [function read(buffer, offset, typeArgs, context) { | |
var args = _.cloneDeep(defaultTypeArgs); | |
argPos.forEach((v) => { | |
setField(v.path, typeArgs[v.val], args); | |
}); | |
return functions[0](buffer, offset, args, context); | |
}, function write(value, buffer, offset, typeArgs, context) { | |
var args = _.cloneDeep(defaultTypeArgs); | |
argPos.forEach((v) => { | |
setField(v.path, typeArgs[v.val], args); | |
}); | |
return functions[1](buffer, offset, args, context); | |
}, function sizeOf(value, typeArgs, context) { | |
var args = _.cloneDeep(defaultTypeArgs); | |
argPos.forEach((v) => { | |
setField(v.path, typeArgs[v.val], args); | |
}); | |
if (typeof functions[2] === "function") | |
return functions[2](buffer, offset, args, context); | |
else | |
return functions[2]; | |
}] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment