Skip to content

Instantly share code, notes, and snippets.

@nonsensecreativity
Forked from tejacques/autowrap.js
Created June 12, 2017 09:59
Show Gist options
  • Save nonsensecreativity/cc36150de0de73d0ba5ecbaa4d291e74 to your computer and use it in GitHub Desktop.
Save nonsensecreativity/cc36150de0de73d0ba5ecbaa4d291e74 to your computer and use it in GitHub Desktop.
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;
import libRaw from './testlib';
import autowrap from './autowrapr';
let lib = autowrap(libRaw);
console.log(lib);
lib.nested.fun1("Hello world");
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