-
-
Save nonsensecreativity/cc36150de0de73d0ba5ecbaa4d291e74 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
let wrappable = { | |
'object': true, | |
'function': true | |
}; | |
let autowrapSymbol = '@@autowrap'; | |
function wrap(fn) { | |
console.log('wrapping function call'); | |
let wrapped = function() { | |
console.log("WRAPPED FUNCTION CALL"); | |
fn.apply(this, arguments); | |
} | |
//wrapped.prototype = fn.prototype; | |
return wrapped; | |
} | |
function autowrap(arg, trace) { | |
if (!(typeof(arg) in wrappable) | |
|| arg === null) { | |
return arg; | |
} | |
trace = trace || {}; | |
trace['@@self'] = trace['@@self'] || []; | |
let wrapped = {}; | |
if (typeof(arg) === 'function') { | |
let prototypes = Object.keys(arg.prototype); | |
if (prototypes.length) { | |
wrapped = function() { | |
return arg.apply(this, arguments); | |
}; | |
trace['@@self'].push([arg, wrapped]); | |
wrapped.prototype = autowrap(arg.prototype, trace); | |
wrapped.prototype.prototype = arg.prototype; | |
} else { | |
wrapped = wrap(arg); | |
trace['@@self'].push([arg, wrapped]); | |
} | |
} else { | |
trace['@@self'].push([arg, wrapped]); | |
} | |
wrapProperties(arg, wrapped, trace); | |
return wrapped; | |
} | |
function wrapProperties(arg, wrapped, trace) { | |
for(let key in arg) { | |
if (!arg.hasOwnProperty(key)) { | |
continue | |
} | |
console.log('wrapping ', key); | |
let original = arg[key]; | |
trace[key] = trace[key] || []; | |
let cmp = ([orig, wrped]) => orig === original; | |
let found = trace['@@self'].filter(cmp); | |
if (!found.length) { | |
found = trace[key].filter(cmp); | |
} | |
if (found.length) { | |
let [orig, wrped] = found[0]; | |
wrapped[key] = wrped; | |
continue; | |
} | |
wrapped[key] = autowrap(original, trace); | |
trace[key].push([original, wrapped[key]]); | |
} | |
} | |
export default autowrap; |
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
import libRaw from './testlib'; | |
import autowrap from './autowrapr'; | |
let lib = autowrap(libRaw); | |
console.log(lib); | |
lib.nested.fun1("Hello world"); |
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
export default { | |
fun1(x) { console.log(x); }, | |
fun2() {}, | |
nested: { | |
fun1(x) { console.log(x); } | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment