Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda