Skip to content

Commit 8732dde

Browse files
committed
Add solution #2627
1 parent 3bf762c commit 8732dde

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,7 @@
369369
2621|[Sleep](./2621-sleep.js)|Easy|
370370
2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium|
371371
2623|[Memoize](./2623-memoize.js)|Medium|
372+
2627|[Debounce](./2627-debounce.js)|Medium|
372373
2629|[Function Composition](./2629-function-composition.js)|Easy|
373374
2630|[Memoize II](./2630-memoize-ii.js)|Hard|
374375
3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy|

solutions/2627-debounce.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 2627. Debounce
3+
* https://leetcode.com/problems/debounce/
4+
* Difficulty: Medium
5+
*
6+
* Given a function fn and a time in milliseconds t, return a debounced version of that function.
7+
*
8+
* A debounced function is a function whose execution is delayed by t milliseconds and whose
9+
* execution is cancelled if it is called again within that window of time. The debounced
10+
* function should also receive the passed parameters.
11+
*
12+
* For example, let's say t = 50ms, and the function was called at 30ms, 60ms, and 100ms.
13+
*
14+
* The first 2 function calls would be cancelled, and the 3rd function call would be executed
15+
* at 150ms.
16+
*
17+
* If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms,
18+
* and the 3rd would be executed at 135ms.
19+
*/
20+
21+
/**
22+
* @param {Function} fn
23+
* @param {number} t milliseconds
24+
* @return {Function}
25+
*/
26+
var debounce = function(fn, t) {
27+
let timer;
28+
return (...args) => {
29+
clearTimeout(timer);
30+
timer = setTimeout(() => fn(...args), t);
31+
};
32+
};

0 commit comments

Comments
 (0)