2023-12-09 18:42:21 +08:00
|
|
|
|
<p>请你写一个函数 <code>createCounter</code>。这个函数接收一个初始的整数值 <code>init</code>。并返回一个包含三个函数的对象。</p>
|
2023-05-15 17:43:00 +08:00
|
|
|
|
|
|
|
|
|
<p>这三个函数是:</p>
|
|
|
|
|
|
|
|
|
|
<ul>
|
|
|
|
|
<li><code>increment()</code> 将当前值加 1 并返回。</li>
|
|
|
|
|
<li><code>decrement()</code> 将当前值减 1 并返回。</li>
|
|
|
|
|
<li><code>reset()</code> 将当前值设置为 <code>init</code> 并返回。</li>
|
|
|
|
|
</ul>
|
|
|
|
|
|
|
|
|
|
<p> </p>
|
|
|
|
|
|
|
|
|
|
<p><strong class="example">示例 1:</strong></p>
|
|
|
|
|
|
|
|
|
|
<pre>
|
2023-12-09 18:42:21 +08:00
|
|
|
|
<strong>输入:</strong>init = 5, calls = ["increment","reset","decrement"]
|
|
|
|
|
<strong>输出:</strong>[6,5,4]
|
2023-05-15 17:43:00 +08:00
|
|
|
|
<strong>解释:</strong>
|
|
|
|
|
const counter = createCounter(5);
|
|
|
|
|
counter.increment(); // 6
|
|
|
|
|
counter.reset(); // 5
|
|
|
|
|
counter.decrement(); // 4
|
|
|
|
|
</pre>
|
|
|
|
|
|
|
|
|
|
<p><strong class="example">示例 2:</strong></p>
|
|
|
|
|
|
|
|
|
|
<pre>
|
2023-12-09 18:42:21 +08:00
|
|
|
|
<strong>输入:</strong>init = 0, calls = ["increment","increment","decrement","reset","reset"]
|
|
|
|
|
<strong>输出:</strong>[1,2,1,0,0]
|
2023-05-15 17:43:00 +08:00
|
|
|
|
<strong>解释:</strong>
|
|
|
|
|
const counter = createCounter(0);
|
|
|
|
|
counter.increment(); // 1
|
|
|
|
|
counter.increment(); // 2
|
|
|
|
|
counter.decrement(); // 1
|
|
|
|
|
counter.reset(); // 0
|
|
|
|
|
counter.reset(); // 0
|
|
|
|
|
</pre>
|
|
|
|
|
|
|
|
|
|
<p> </p>
|
|
|
|
|
|
|
|
|
|
<p><strong>提示:</strong></p>
|
|
|
|
|
|
|
|
|
|
<ul>
|
|
|
|
|
<li><code>-1000 <= init <= 1000</code></li>
|
2023-12-09 18:42:21 +08:00
|
|
|
|
<li><code>0 <= calls.length <= 1000</code></li>
|
|
|
|
|
<li><code>calls[i]</code> 是 “increment”、“decrement” 和 “reset” 中的一个</li>
|
2023-05-15 17:43:00 +08:00
|
|
|
|
</ul>
|