-
-
Save modernserf/6f440867375f5951f3b7cc368637c700 to your computer and use it in GitHub Desktop.
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
const isolate = (scope) => | |
new Proxy(scope, { | |
has: () => true, | |
get: (target, key) => { | |
if (key === Symbol.unscopables) { | |
return undefined | |
} | |
if (key in target) { | |
return target[key] | |
} | |
throw new ReferenceError(`${key} is not defined`) | |
} | |
}) | |
with (isolate({ console, foo: "foo" })) { | |
console.log(foo) // "foo" | |
console.log("bar") // "bar" | |
console.log(window) // ReferenceError "window is not defined" | |
} | |
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
const isolate = (source, ...exposedVariables) => | |
new Proxy(source, { | |
has: (_, key) => !exposedVariables.includes(key), | |
get: (target, key) => { | |
if (key === Symbol.unscopables) { | |
return undefined | |
} | |
if (key in target) { | |
return target[key] | |
} | |
throw new ReferenceError(`${key} is not defined`) | |
} | |
}) | |
let foo = 1 | |
let bar = 2 | |
let baz = 3 | |
with (isolate(Math, "console", "foo", "bar")) { | |
console.log(min(foo, bar)) // 1 | |
console.log(min(bar, baz)) // ReferenceError: baz is not defined | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment