|
| 1 | +// Question Link: https://leetcode.com/problems/counter-ii/?envType=study-plan-v2&envId=30-days-of-javascript |
| 2 | +// Solution Link: https://leetcode.com/problems/counter-ii/solutions/5424118/easty-javascript-solution-using-arrow-function-time-space-complexity-o-1/ |
| 3 | + |
| 4 | +/* |
| 5 | +2665. Counter II |
| 6 | +
|
| 7 | +Write a function createCounter. It should accept an initial integer init. It should return an object with three functions. |
| 8 | +
|
| 9 | +The three functions are: |
| 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 | +Example 1: |
| 15 | +Input: init = 5, calls = ["increment","reset","decrement"] |
| 16 | +Output: [6,5,4] |
| 17 | +Explanation: |
| 18 | +const counter = createCounter(5); |
| 19 | +counter.increment(); // 6 |
| 20 | +counter.reset(); // 5 |
| 21 | +counter.decrement(); // 4 |
| 22 | +Example 2: |
| 23 | +Input: init = 0, calls = ["increment","increment","decrement","reset","reset"] |
| 24 | +Output: [1,2,1,0,0] |
| 25 | +Explanation: |
| 26 | +const counter = createCounter(0); |
| 27 | +counter.increment(); // 1 |
| 28 | +counter.increment(); // 2 |
| 29 | +counter.decrement(); // 1 |
| 30 | +counter.reset(); // 0 |
| 31 | +counter.reset(); // 0 |
| 32 | + |
| 33 | +Constraints: |
| 34 | +-1000 <= init <= 1000 |
| 35 | +0 <= calls.length <= 1000 |
| 36 | +calls[i] is one of "increment", "decrement" and "reset" |
| 37 | +*/ |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | +/** |
| 42 | + * @param {integer} init |
| 43 | + * @return { increment: Function, decrement: Function, reset: Function } |
| 44 | + */ |
| 45 | +var createCounter = function(init) { |
| 46 | + let num = init; |
| 47 | + |
| 48 | + return { |
| 49 | + increment: () => { |
| 50 | + return ++num; |
| 51 | + }, |
| 52 | + decrement: () => { |
| 53 | + return --num; |
| 54 | + }, |
| 55 | + reset: () => { |
| 56 | + num = init; |
| 57 | + return num; |
| 58 | + } |
| 59 | + } |
| 60 | +}; |
| 61 | + |
| 62 | +/** |
| 63 | + * const counter = createCounter(5) |
| 64 | + * counter.increment(); // 6 |
| 65 | + * counter.reset(); // 5 |
| 66 | + * counter.decrement(); // 4 |
| 67 | + */ |
0 commit comments