-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounterII.js
118 lines (98 loc) · 2.84 KB
/
CounterII.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
LeetCode Task:
Write a function createCounter. It should accept an initial integer init. It should return an object with three functions.
The three functions are:
increment() increases the current value by 1 and then returns it.
decrement() reduces the current value by 1 and then returns it.
reset() sets the current value to init and then returns it.
*/
// Class
// class Counter {
// constructor(init) {
// this.init = init;
// this.currentCount = init;
// }
// increment() {
// this.currentCount += 1;
// return this.currentCount;
// }
// decrement() {
// this.currentCount -= 1;
// return this.currentCount;
// }
// reset() {
// this.currentCount = this.init;
// return this.currentCount;
// }
// }
// const createCounter = function(init) {
// return new Counter(init)
// }
// Closure with Proxy
// const createCounter = function(init) {
// let currentCount = init;
// return new Proxy({}, {
// get: (target, key) => {
// switch (key) {
// case "increment":
// return () => ++currentCount;
// case "decrement":
// return () => --currentCount;
// case "reset":
// return () => (currentCount = init);
// default:
// throw Error("Unexpected Method")
// }
// }
// })
// }
// Closure
// const createCounter = function(init) {
// let currentCount = init;
// return {
// increment: function() {
// currentCount += 1;
// return currentCount
// },
// decrement: function() {
// currentCount -= 1;
// return currentCount;
// },
// reset: function() {
// currentCount = init;
// return currentCount;
// }
// }
// }
// Closure with Separately Created Functions
// const createCounter = function(init) {
// let currentCount = init;
// function increment() {
// return ++currentCount;
// }
// function decrement() {
// return --currentCount
// }
// function reset() {
// return currentCount = init;
// }
// return {increment, decrement, reset}
// }
// Closure with Shortened Syntax
const createCounter = function(init) {
let currentCount = init;
return {
increment: () => ++currentCount,
decrement: () => --currentCount,
reset: () => (currentCount = init),
}
}
const counter = createCounter(5)
console.log(counter.decrement())
console.log(counter.increment())
console.log(counter.increment())
console.log(counter.decrement())
console.log(counter.decrement())
console.log(counter.increment())
console.log(counter.increment())
console.log(counter.reset())