mercredi 17 novembre 2021

Undo/redo memento pattern Javascript

Relatively new to the Design patterns, Generally my works are writing function for the needs. But now i need to implement a undo redo functionality, so i just read about the different patterns which i can use for that and found that, memento pattern is the one we can go for. So try to write the code to implement that, It's worked, but not sure about the code quality. Also not actually follow the JAVA style Memento pattern, Here i am understand the concept and add code my own way.

const Calculator = () => {
    const mementos = [];
    let redos = [];
    let sum = 0;
    const add = (num) => {
        setState(sum);
        sum += num;
    };
    const sub = (num) => {
        setState(sum);
        sum -= num;
    }
    const mul = (num) => {
        setState(sum);
        sum *= num;
    }
    const div = (num) => {
        setState(sum);
        sum /= num;
    }
    const setState = (state) => {
        mementos.push({
            state
        });
    };
    const restore = state => state.state;
    const undo = () => {
        redos = [];
        if (mementos.length <= 0) {
            return null;
        }
        redos.push({
            state: sum
        });
        const memento = mementos.pop();
        sum = restore(memento);
        return sum;
    };
    const redo = () => {
        if (redos.length <= 0) {
            const obj = redos.pop();
            sum = restore(obj);
        }
    };
    return {
        add,
        sub,
        mul,
        div,
        undo,
        redo,
        dispaly: () => {
            console.log(sum);
        }
    };
};

const {
    sub,
    mul,
    div,
    dispaly,
    add,
    undo,
    redo
} = Calculator();

add(10);
dispaly();
add(50);
dispaly();
sub(10);
dispaly();
mul(2);
dispaly();
undo();
dispaly();

Any issues with this coding style or any improvements i can add on this to make this pattern is maintainable. Thank You

Aucun commentaire:

Enregistrer un commentaire