Skip to content
Advertisement

Is there a way to override Object to instantiate a property upon attempting to modify it?

I feel like the answer to this is a hard no in most languages I’ve used other than PHP, which at least used to have some odd corner cases with stuff like $someArray['nonexistentKey']++.

I’m basically looking to write a sparse object where each property is a numeric counter. The counters should return 0 if undefined and should automatically define themselves with a value of 0 if you try to increment them.

In other words, I want to override the generic Object getter to return 0 in all cases where it would return undefined… or perhaps define the property right there during the get and set it to 0.

So in theory, an overload for ANY property not yet defined would get initialize it at zero. For example this:

myObj['hugePrimeNumberToBaseXToString']++;

would then make it 1.

In the olden days I feel like some way with Object.__proto__ might have worked for this case…

Advertisement

Answer

I think what you want is a Proxy.

You can use a proxy to intercept property gets and return your own logic. In this case, return zero in the case of an undefined property.

// Hold the data
const target: { [key in string]: number } = {}

// Access the data
const proxy = new Proxy(target, {
    get(target, prop, receiver) {
        if (typeof prop === 'string') {
            if (target[prop] === undefined) return 0
            return target[prop]
        }
        return undefined
    }
})

proxy['hugePrimeNumberToBaseXToString']++
console.log(proxy['hugePrimeNumberToBaseXToString']) //=> 1

Playground

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement