Skip to content

Instantly share code, notes, and snippets.

@bga
Created December 7, 2017 15:34
Show Gist options
  • Save bga/f4794c52db0ba7945a88c82218fd6a40 to your computer and use it in GitHub Desktop.
Save bga/f4794c52db0ba7945a88c82218fd6a40 to your computer and use it in GitHub Desktop.
Object.getRealmOf.js
#!/usr/bin/env node
"use strict"
//const global = (typeof(global) != "undefined") ? global : this
//# or { null } if you dont want cache
let cache = new WeakMap()
const isPrimitive = (v) => {
return v !== Object(v)
}
;(global.Reflect || { }).getRealmOf = Object.getRealmOf = function(obj) {
if(isPrimitive(obj)) {
return null
}
else {
const objProto = Object.getPrototypeOf(obj)
if(objProto == null) {
return null
}
else {
const RealmFunction = (objProto
.constructor // Class
.constructor // Function
)
if(RealmFunction == Function) {
return global
}
else {
const getAndCache = function(get) {
if(cache != null) {
let tmp = null
return cache.get(RealmFunction) || (tmp = get(), cache.set(RealmFunction, tmp), tmp)
}
else {
return get()
}
}
return getAndCache(() => RealmFunction("return this")())
}
}
}
}
const example = (f) => {
try {
f()
}
catch(err) {
console.log(`Test failded, err = #{ err }`)
throw err
}
console.log("Test passed")
}
const assert = function(expr, msg) {
if(!expr) {
throw msg || ""
}
else {
}
}
example(() => {
assert(Object.getRealmOf("") == null)
assert(Object.getRealmOf(Object.create(null)) == null)
assert(Object.getRealmOf([]) == global)
let createRealm = null
if(global.require != null && global.require("vm") != null) {
const vm = require("vm")
createRealm = function() {
const sandbox = { }
vm.createContext(sandbox)
return {
sandbox,
eval(code) {
vm.runInContext(code, sandbox)
}
}
}
}
else {
}
if(createRealm != null) {
let realm = createRealm()
assert(Object.getRealmOf(realm.eval("[]")) == realm.eval("this"))
}
else {
}
})
//# typical usecases
example(function() {
let obj = []
assert(obj instanceof Object.getRealmOf(obj).Array)
assert(obj instanceof Object.getRealmOf(obj).Object)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment