forked from tzeikob/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
44 lines (32 loc) · 764 Bytes
/
calculator.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
var myNS = myNS || Object.create(null);
myNS.Calculator = function Calculator() {
this.result = 0;
this.commands = [];
};
myNS.Calculator.prototype.add = function add(value) {
this.result += value;
return this.result;
};
myNS.Calculator.prototype.execute = function execute(name, ...args) {
if (this[name]) {
this.commands.push({
name,
args
});
return this[name].apply(this, args);
}
return false;
};
myNS.Calculator.prototype.replay = function replay() {
this.result = 0;
this.commands.forEach(c => {
this[c.name].apply(this, c.args);
});
};
let c = new myNS.Calculator();
c.execute('add', 22);
c.execute('add', -3);
console.log(c.result); // 19
c.result = 666;
c.replay();
console.log(c.result); // 19