Skip to content

Instantly share code, notes, and snippets.

@tejacques
Last active June 12, 2017 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tejacques/1988522d7882aabe0e40 to your computer and use it in GitHub Desktop.
Save tejacques/1988522d7882aabe0e40 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