Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!