Skip to content

Instantly share code, notes, and snippets.

@dmitry-vsl
Created January 5, 2014 19:43
Show Gist options
  • Save dmitry-vsl/8272857 to your computer and use it in GitHub Desktop.
Save dmitry-vsl/8272857 to your computer and use it in GitHub Desktop.
implementation of this function http://underscorejs.org/#debounce in D programming language (http://dlang.org)
#!/usr/bin/env rdmd
// implementation of this function http://underscorejs.org/#debounce
// in D programming language (http://dlang.org)
import std.stdio;
import std.datetime;
void test(double a){
writeln("Invoked debounced func with ", a);
}
void delegate(Args) debounce(Args...)
(void function(Args) func,
long interval ){
long time = 0;
void debounced(Args args){
long newTime = Clock.currTime().stdTime();
if(newTime - time > interval){
func(args);
}
time = newTime;
};
return &debounced;
}
void main(){
auto func = debounce(&test,5000000);
while(readln()){
func(1.0);
}
}
@John-Colvin
Copy link

A little more generic:

import std.stdio;
import std.datetime;
import std.traits;

void test(double a)
{
    writeln("Invoked debounced func with ", a);
}

auto debounce(Callable)(Callable func, Duration interval)
    if(isCallable!Callable)
{
    auto time = SysTime(0);
    void debounced(ParameterTypeTuple!func args)
    {
        auto newTime = Clock.currTime();
        if(newTime - time > interval)
        {
            func(args);
        }
        time = newTime;
    }
    return &debounced;
}

void main()
{
    auto func = debounce(&test,500.msecs);
    while(readln())
    {
        func(1.0);
    }
}

Also, debounced is a closure, which AFAIK causes a heap allocation. Not a problem unless you're writing hard-realtime code or are calling debounce a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment