Skip to content

Commit b8e7b9a

Browse files
committedJun 29, 2020
Debounce function - Facebook
1 parent 11b367b commit b8e7b9a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
 

‎Solution/Day-105.cpp

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include <bits/stdc++.h>
2+
#include <stdexcept>
3+
using namespace std;
4+
using namespace chrono;
5+
6+
function<void()> Debounced(function<void()>&f , int period){
7+
static auto created = high_resolution_clock::now();
8+
function<void()> fn = [=,&f](){
9+
auto now = high_resolution_clock::now();
10+
if (duration_cast<milliseconds>(now - created).count() > period){
11+
f();
12+
}
13+
// created = now; // mark the last call of the function
14+
15+
// For debouncing uncomment the above line, So we will mark the time for last
16+
// call made to this function and would call it again only if time difference is greater
17+
// then the period provided
18+
};
19+
return fn;
20+
}
21+
22+
int main(void){
23+
int x = 0;
24+
function<void()> f = [&x](){
25+
x++;
26+
};
27+
28+
auto dbf = Debounced(f, 500);
29+
for (int i = 0; i < 10; ++i) {
30+
dbf();
31+
}
32+
// we can't call this function until 500ms period is over.
33+
if (x != 0) {
34+
throw std::runtime_error("Expected x not to change since it's debounced for 500ms");
35+
}
36+
std::this_thread::sleep_for(milliseconds(501)); // 500 (inclusive) is threshold so let the
37+
// thread sleep for 501ms
38+
39+
// now we can call this function as many time we want
40+
for (int i = 0; i < 10; ++i) {
41+
dbf();
42+
}
43+
if (x != 10) {
44+
throw std::runtime_error("Expected x to be incremented 10 times");
45+
}
46+
}

0 commit comments

Comments
 (0)
Please sign in to comment.