Skip to content

Instantly share code, notes, and snippets.

@huynhducduy
Created July 12, 2024 06:20
Show Gist options
  • Save huynhducduy/029d83e6bbdd9b9641ace0c1ed99745e to your computer and use it in GitHub Desktop.
Save huynhducduy/029d83e6bbdd9b9641ace0c1ed99745e to your computer and use it in GitHub Desktop.
Wrap a function in `isolate` to prevent it from create closure.
export default function isolate<T extends (...args: unknown[]) => unknown>(fn: T): T {
// eslint-disable-next-line @typescript-eslint/no-implied-eval -- workaround
return new Function(`
with (new Proxy({}, {
has () { return true; },
get (target, property) {
if (typeof property !== 'string') return target[property];
throw new ReferenceError(property + ' accessed from isolated scope');
},
set (target, property) {
throw new ReferenceError(property + ' accessed from isolated scope');
}
})) return ${Function.prototype.toString.call(fn)}
`).call(
new Proxy(
function () {
/* do nothing */
},
new Proxy(
{},
{
get() {
throw new ReferenceError('this accessed from isolated scope')
},
},
),
),
) as T
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment