forked from damiancipolat/Nodejs-Design-Pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.js
71 lines (53 loc) · 1.59 KB
/
command.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const add=(x, y)=> { return x + y; }
const sub=(x, y)=> { return x - y; }
const mul=(x, y)=> { return x * y; }
const div=(x, y)=> { return x / y; }
const Command = (execute, undo, value)=> {
this.execute = execute;
this.undo = undo;
this.value = value;
}
const AddCommand = (value)=>{
return new Command(add, sub, value);
};
const SubCommand = (value)=>{
return new Command(sub, add, value);
};
const MulCommand = (value)=> {
return new Command(mul, div, value);
};
const DivCommand = (value)=> {
return new Command(div, mul, value);
};
const Calculator = function () {
let current = 0;
let commands = [];
const action=(command)=> {
var name = command.execute.toString().substr(9, 3);
return name.charAt(0).toUpperCase() + name.slice(1);
}
return {
execute: function (command) {
current = command.execute(current, command.value);
commands.push(command);
log.add(action(command) + ": " + command.value);
},
undo: function () {
var command = commands.pop();
current = command.undo(current, command.value);
log.add("Undo " + action(command) + ": " + command.value);
},
getCurrentValue: function () {
return current;
}
}
}
function run() {
var calculator = new Calculator();
calculator.execute(new AddCommand(100));
calculator.execute(new SubCommand(24));
calculator.execute(new MulCommand(6));
calculator.execute(new DivCommand(2));
calculator.undo();
calculator.undo();
}