Using immutability-helper, how to set the property of an instance of a class without cloning other fields?

168 Views Asked by At

Here is an example:

class ExampleClass {
    private x: number;
    private ary: number[];

    constructor(x, ary = []) {
        this.x = x;
        this.ary = ary;
    }

    public getX() {
        return this.x;
    }

    public setX(x) {
        this.x = x;
    }
}

const elemArray = [new ExampleClass(10, [10, 20]), new ExampleClass(20, [20, 30])];

I want to set the elemArray's second element's x to 30 using the setX function. The simplest way would be:

const newElemArray = update(elemArray, {1: {$apply: function (x: ExampleClass) {
    const y = _.cloneDeep(x);
    y.setX(30); 
    return y;
}}});

But I want to be able to do this without cloning the array ary, since that can itself be large and cloning maybe costly. How can I do this?

Thanks

0

There are 0 best solutions below