Skip to content

Instantly share code, notes, and snippets.

@modernserf
Last active December 31, 2018 03:32
Show Gist options
  • Save modernserf/6f440867375f5951f3b7cc368637c700 to your computer and use it in GitHub Desktop.
Save modernserf/6f440867375f5951f3b7cc368637c700 to your computer and use it in GitHub Desktop.
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"
}
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