JSFiddle - React, Tailwind, and code Playground
JavaScript
// ######################################################
// define three functions
var x = function() {
var a = 'hello';
console.log(a);
};
var y = function() {
console.log('y');
asd // error
};
var run = function(xx, yy) {
xx();
yy();
console.log('done!');
};
// ######################################################
// function-to-string code
var serializeFunction = function(fun, name) {
var codeStr = '(' + fun.toString() + ')';
codeStr += '\n//# sourceURL=' + encodeURIComponent(name);
codeStr = JSON.stringify(codeStr);
return 'eval(eval(' + codeStr + '))';
}
// ######################################################
// convert functions to strings
var xCode = serializeFunction(x, 'function_x');
var yCode = serializeFunction(y, 'function_y');
var runCode = serializeFunction(run, 'function_run');
var finalCode = 'runCode + "(" + xCode + ", " + yCode + ")"';
// ######################################################
// At this point xCode, yCode and runCode are r-valued function definitions in string form.
// The difference is:
// 1. These guys will produce a meaningful stacktrace.
// 2. And we can embed them with other code in any way we want.
// Example:
try {
eval(eval(finalCode));
}
catch (err) {
console.log(err.stack);
}