neaumusic
neaumusic

Reputation: 10454

ES6 setter - keep object CLEAN // map params on instance object

I want to wrap values in an Array, whenever they're set on my object, but I want to keep the "global" object namespace CLEAN

The problem is that I have a list of 8 props that have this same requirement

I don't want the object to be polluted with tons of get and set, plus the this._left to avoid infinite loop when setting the same prop that's monitored by the setter....

For example:

class Tree {
    constructor (config) {
        this.left = config.left || [this];
        this.right = config.right || [this];
        this.child = config.child || [this];
        this.parent = config.parent || [this];
        this.somethingElse = config.somethingElse || [this];
        // etc.
    }
}

myObj = new Tree();

myObj.left = 2;

I want to ensure that myObj.next === [2]


My attempt (too polluted):

['left', 'right', 'child', 'parent', 'etc', 'adfasdf', 'dsfmkfs', 'previous'].forEach(direction => {
    Object.defineProperty(this, prop, {
        set: (val) => {
            if (!Array.isArray(val)) {
                this['_' + prop] = [val]
            } else {
                this['_' + prop] = val;
            }
        },
        get: (val) => {
            return this['_' + prop];
        }
    });
});

Upvotes: 0

Views: 47

Answers (1)

Bergi
Bergi

Reputation: 664356

You cannot have setters/getters without setters/getters. However, you don't necessarily need those underscore-prefixed properties to store the values:

['left', 'right', 'child', 'parent', 'etc', 'adfasdf', 'dsfmkfs', 'previous'].forEach(prop => {
    var value = [this];
    Object.defineProperty(this, prop, {
        set(val) {
            if (!Array.isArray(val)) {
                val = [val];
            }
            value = val;
        },
        get(val) {
            return value;
        },
        enumerable: true,
        configurable: true
    });
});

Upvotes: 1

Related Questions