'The best way to implement override data state from parent class

I'm facing a really hard problem. I want to create a wrapper class that can do something like "override" the state of the child without affecting the child's state. Quite hard to understand, I know.

Let's see some minimal code below:

class State{
    key: string; //Unique key
    //This is really complex, nested, array, etc state.
    value: number | string | State | State[] | any
}

class Child{
    state : State;
}
class Wrapper{
    overrideState: State;
    child: Child;
    
    constructor(child: Child){
        this.child = child;
    }

    getFinalState() : State{
        //This will return the new State (or not), that is the final state
    }
}

A function to call them:

function client(){
    let child = new Child();
    child.state = new State();
    child.state.value = {}
    child.state.value.a = "a value original";
    child.state.value.b = "b value original";

    let parent = new Wrapper(child);
    parent.overrideState = new State();
    parent.overrideState.value = {}
    parent.overrideState.value.a = "overrided"
    parent.overrideState.value.c = "c overrided"


    console.log(parent.getFinalState().value.a); //It should be `overrided`, 
    console.log(child.state.value.a); //It should still `a value original`, 
    console.log(parent.getFinalState().value.b); //It should be `b value original`, 
    console.log(parent.getFinalState().value.c); //It should be `undefined` because c is not exists in `Child`, 
}

The problem is State class is really complex.

Actually, I have almost done with the getFinalState function by using looping, checking type, Lodash.cloneDeep,...a ton of code. And I think it's really complex to maintain, hard to read, and maybe has some risk.

I don't think my way is right, I try to research some design patterns but am still stuck. If you have any ideas, keywords, or something. I really appreciate that. Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source