|
| 1 | +/** |
| 2 | + * 2665 |
| 3 | + * Counter II |
| 4 | + ** |
| 5 | + * Write a function createCounter. |
| 6 | + * It should accept an initial integer init. |
| 7 | + * 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 | + * |
| 23 | + * Example 2: |
| 24 | + * Input: init = 0, calls = ["increment","increment","decrement","reset","reset"] |
| 25 | + * Output: [1,2,1,0,0] |
| 26 | + * Explanation: |
| 27 | + * const counter = createCounter(0); |
| 28 | + * counter.increment(); // 1 |
| 29 | + * counter.increment(); // 2 |
| 30 | + * counter.decrement(); // 1 |
| 31 | + * counter.reset(); // 0 |
| 32 | + * counter.reset(); // 0 |
| 33 | + * |
| 34 | + * Constraints: |
| 35 | + * • -1000 <= init <= 1000 |
| 36 | + * • 0 <= calls.length <= 1000 |
| 37 | + * • calls[i] is one of "increment", "decrement" and "reset" |
| 38 | + * |
| 39 | + * Hint 1: |
| 40 | + * You can return an object with methods. |
| 41 | + * |
| 42 | + * Hint 2: |
| 43 | + * Initialize a variable for currentCount. |
| 44 | + * Inside these methods, |
| 45 | + * add the appropriate logic which mutates currentCount. |
| 46 | + ** |
| 47 | + * https://leetcode.com/problems/counter-ii/ |
| 48 | +***/ |
| 49 | + |
| 50 | +/** |
| 51 | + * @param {integer} init |
| 52 | + * @return { increment: Function, decrement: Function, reset: Function } |
| 53 | +***/ |
| 54 | +const createCounter = function(init) { |
| 55 | + let count = init; |
| 56 | + |
| 57 | + return { |
| 58 | + increment() { |
| 59 | + return ++count; |
| 60 | + }, |
| 61 | + decrement() { |
| 62 | + return --count; |
| 63 | + }, |
| 64 | + reset() { |
| 65 | + return (count = init); |
| 66 | + } |
| 67 | + } |
| 68 | +}; |
| 69 | + |
| 70 | +/** |
| 71 | + * const counter = createCounter(5) |
| 72 | + * counter.increment(); // 6 |
| 73 | + * counter.reset(); // 5 |
| 74 | + * counter.decrement(); // 4 |
| 75 | +***/ |
| 76 | + |
| 77 | +module.exports = createCounter; |
0 commit comments