[Easy] LeetCode JS 30 - 2665. Counter II (計數器 II)

2024年3月5日

💎 加入 E+ 成長計畫 與超過 300+ 位軟體工程師一同在社群中成長,並且獲得更多的軟體工程學習資源

LeetCode 30 Days of JavaScript

本題來自 LeetCode 的 30 天 JacaScript 挑戰

2665. Counter II (計數器 II)

題目描述

想像你正在開發一個需要追蹤各種指標的功能。我們需要在程式碼中,用彈性的方式管理計數器。你的任務是設計一個名為 createCounter 的函式,可用於生成具有特定起始值的客製化計數器。

createCounter 將返回一個具有以下方法的物件:

  • get():返回計數器的當前值。
  • increment():將計數器值增加 1 並返回更新后的值。
  • decrement():將計數器值減少 1 並返回更新后的值。
  • reset():將計數器重置回其初始值。
const counter = createCounter(4);
counter.get(); // 4
counter.increment(); // 5
counter.increment(); // 6
counter.get(); // 6
counter.reset(); // 4
counter.decrement(); // 3

本題解答

以下是本題的解答,詳細解題思路可以在 E+ 成長計畫看到

解法一

function createCounter(initialValue = 0) {
  let value = initialValue;

  function get() {
    return value;
  }

  function increment() {
    value += 1;
    return value;
  }

  function decrement() {
    value -= 1;
    return value;
  }

  function reset() {
    value = initialValue;
    return value;
  }

  return {
    get,
    increment,
    decrement,
    reset,
  };
}

解法二

class Counter {
  constructor(initialValue = 0) {
    this.initialValue = initialValue;
    this.value = initialValue;
  }
  get() {
    return this.value;
  }
  increment() {
    this.value += 1;
    return this.value;
  }
  decrement() {
    this.value -= 1;
    return this.value;
  }
  reset() {
    this.value = this.initialValue;
    return this.value;
  }
}

function makeCounter(initialValue = 0) {
  return new Counter(initialValue);
}
🧵 如果你想收到最即時的內容更新,可以在 FacebookInstagram 上追蹤我們