Created
March 23, 2021 20:07
-
-
Save brimonk/4428952eb9382f6c77fc0f318c4d836e to your computer and use it in GitHub Desktop.
I was debugging some stuff in control-flow hell at work, and thought this might be useful. `eval()` outside of `<script>` tags doesn't work, but apparently it's just fine inside them.
This file contains hidden or 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
<html> | |
<script> | |
function addone(v) { return v + 1; } | |
function debugify(fn) { | |
console.log("debugifying"); | |
let source = fn.toString(); | |
let parts = source.split(" "); | |
let decl = parts[1]; | |
let name = decl.replace(/\(.+\)/, ""); | |
let params = decl.replace(/.+\(/, "").replace(/\)/, ""); | |
let body = parts.slice(3, parts.length - 1).join(" "); | |
let newfnsrc = `function ${name}(${params}) { console.log("${name}"); function _${name}(${params}) { ${body} }; return _${name}.apply(this, [${params}]); }`; | |
// return new Function(newfnsrc); | |
const test = eval(`(${newfnsrc})`); | |
return test; | |
} | |
const dbg = debugify(addone); | |
console.log(dbg(1)); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment