leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

commit 1b9cdc1a4c8e9064db9f94025e15af2d2d669482
parent b992f73a866ea8d18257bbefa9e9ec6ae83241fb
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date:   Sat, 20 May 2023 09:51:00 +0200

JavaScript Challenge: Day 16

Diffstat:
AProblems/2676.js | 29+++++++++++++++++++++++++++++
MREADME.md | 1+
2 files changed, 30 insertions(+), 0 deletions(-)

diff --git a/Problems/2676.js b/Problems/2676.js @@ -0,0 +1,29 @@ +/** + * @param {Function} fn + * @param {number} t + * @return {Function} + */ + +var throttle = function(fn, t) { + let timeoutInProgress = null; + let argsToProcess = null; + + const timeoutFunction = () => { + if (argsToProcess === null) { + timeoutInProgress = null; // enter the waiting phase + } else { + fn(...argsToProcess); + argsToProcess = null; + timeoutInProgress = setTimeout(timeoutFunction, t); + } + }; + + return function throttled(...args) { + if (timeoutInProgress) { + argsToProcess = args; + } else { + fn(...args); // enter the looping phase + timeoutInProgress = setTimeout(timeoutFunction, t); + } + } +}; diff --git a/README.md b/README.md @@ -555,3 +555,4 @@ for solving problems. | 2665 | Easy | [Counter II](Problems/2665.js) | | 2666 | Easy | [Allow One Function Call](Problems/2666.js) | | 2667 | Easy | [Create Hello World Function](Problems/2667.js) | +| 2676 | Medium | [Throttle](Problems/2676.js) |