iT邦幫忙

2023 iThome 鐵人賽

DAY 4
0
Software Development

LELECOCODE 每一天系列 第 4

Day4 : Leetcode 小挑戰,30 Days of JavaScript

  • 分享至 

  • xImage
  •  

DAY 4: Counter II

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.

var createCounter = function(init) {
    
};

Example 1:
Input: init = 5, calls = ["increment","reset","decrement"]
Output: [6,5,4]

Example 2:
Input: init = 0, calls = ["increment","increment","decrement","reset","reset"]
Output: [1,2,1,0,0]


var createCounter = function(init) {
    let currentValue = init;
    return {
        increment: () => currentValue+=1,
        reset: () => currentValue = init,
        decrement: () => currentValue-=1,
    };
};

上一篇
Day3 : Leetcode 小挑戰,30 Days of JavaScript
下一篇
Day 5: Leetcode 小挑戰,30 Days of JavaScript
系列文
LELECOCODE 每一天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言