Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix module proxy to use proxies #4

Open
dead-claudia opened this issue Jul 22, 2018 · 0 comments
Open

Fix module proxy to use proxies #4

dead-claudia opened this issue Jul 22, 2018 · 0 comments

Comments

@dead-claudia
Copy link
Owner

dead-claudia commented Jul 22, 2018

Why not save a bit of memory by using proxies with caching to lighten the footprint of methods? Also, while we're at it, the length is a bit useless, and could probably be shed. (Most of the time functions depend on lengths, they also have a facility to specify it explicitly.)

Example implementation
const methodData = new WeakMap()
const methodCache = new Map()
const hasOwn = Object.prototype.hasOwnProperty
const proxyTarget = Object.create(null)

Object.defineProperty(proxyTarget, Symbol.toStringTag, {
    configurable: false, enumerable: false, writable: false,
    value: "Module Proxy",
})

function compileMethod(name) {
    let memo = methodCache.get(name)

    if (memo == null) {
        methodCache.set(name, memo = /** @this */ function (...args) {
            const {module, options} = methodData.get(this)

            return module.pool.invoke(
                {module, options, name},
                args.length ? args : undefined
            )
        })
    }

    return memo
}

exports.ModuleWrap = class ModuleWrap {
    constructor(pool, name, methods) {
        this.pool = pool
        this.name = name
        this.methods = methods
        this.proxy = this.apply(proxyTarget, undefined, [])
    }

    apply(target, thisArg, [options]) {
        if (options == null || typeof options !== "object") {
            throw new TypeError("`options` must be an object")
        }

        const proxy = new Proxy(target, this)

        methodData.set(proxy, {module: this, options})
        return proxy
    }

    get(target, key, receiver) {
        return hasOwn.call(this.methods, key)
            ? compileMethod(key)
            : Reflect.get(target, key, receiver)
    }

    has(target, key) {
        return hasOwn.call(this.methods, key) || Reflect.has(target, key)
    }

    set() { return false }
    defineProperty() { return false }
    deleteProperty() { return false }
    setPrototypeOf() { return false }
    preventExtensions() { return false }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant