Created
October 8, 2024 18:26
-
-
Save jameswomack/90fdb5e5942da9248e700a07d0bbe495 to your computer and use it in GitHub Desktop.
Root of All Eval
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
class ServiceNowComSource { | |
static sys_id = '67890'; | |
async *#mapHistoryEntry(event) { | |
yield { sys_id: event.sys_id, code: `class ServiceNowComSource { static sys_id = ${event.sys_id} }`, schema_version: '12345', }; | |
} | |
async *mapHistory(history) { | |
for (const event of history) { | |
yield* this.#mapHistoryEntry(event); | |
} | |
} | |
static evaluateSelf () { | |
return (new Function(`${this.toString()}; return ${this.name}.sys_id`)()).toString() | |
} | |
static async demonstrate () { | |
console.info(this.evaluateSelf()); | |
const serviceNow = new ServiceNowComSource(); | |
const history = [{ | |
"sys_id": "12345", | |
"field": "of-dreams", | |
"old_value": "old_value", | |
"new_value": "new_value", | |
}, { | |
"sys_id": "54321", | |
"field": "theory", | |
"old_value": "old_value", | |
"new_value": "new_value", | |
}]; | |
for await (const result of serviceNow.mapHistory(history)) { | |
const executableCode = `${result.code.match(/class (\w+)/)[1]}.sys_id`; | |
eval(`${result.code}; console.log('Retrieved sys_id', ${executableCode}, \`via ${executableCode}\`);`); | |
} | |
} | |
} | |
import.meta.url === `file://${process.argv[1]}` && | |
(async function runDemonstration () { | |
await ServiceNowComSource.demonstrate(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playing around with a couple of the avenues we have for meta-programming in JavaScript