File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+
3+ Counter II
4+
5+ Write a function createCounter. It should accept an initial integer init.
6+ It should return an object with three functions.
7+
8+ The three functions are:
9+
10+ increment() increases the current value by 1 and then returns it.
11+ decrement() reduces the current value by 1 and then returns it.
12+ reset() sets the current value to init and then returns it.
13+
14+
15+ Example 1:
16+
17+ Input: init = 5, calls = ["increment","reset","decrement"]
18+ Output: [6,5,4]
19+ Explanation:
20+ const counter = createCounter(5);
21+ counter.increment(); // 6
22+ counter.reset(); // 5
23+ counter.decrement(); // 4
24+ */
25+
26+ var createCounter = function ( init ) {
27+
28+ let current = init
29+ // return an object
30+ return {
31+
32+ increment : ( ) => {
33+
34+ return ++ current
35+
36+ } ,
37+
38+ decrement : ( ) => {
39+ return -- current
40+ } ,
41+
42+ reset : ( ) => {
43+ current = init
44+ return current
45+ }
46+ }
47+
48+
49+ } ;
50+
51+
52+ const counter = createCounter ( 5 )
53+ console . log ( counter . increment ( ) ) ; // 6
54+ console . log ( counter . increment ( ) ) ; // 7
55+ console . log ( counter . decrement ( ) ) ; // 6
56+ console . log ( counter . reset ( ) ) ; // 5
57+ console . log ( counter . decrement ( ) ) ; // 4
You can’t perform that action at this time.
0 commit comments