JSFiddle - React, Tailwind, and code Playground

by blesh

JavaScript

function debounce(delay, fn) {
    var timeout;
    return function () {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        var args = toArray(arguments);
        timeout = setTimeout(function (){
            fn.apply(this, args);
        }, delay);
    };
};

function throttle(delay, fn) {
    var timeout;
    return function () {
        if (timeout) {
            return;
        }
        var args = toArray(arguments);
        timeout = setTimeout(function () {
            fn.apply(this, args);
            timeout = null;
        }, delay);
    };
}
function toArray(x) {
    return [].slice.call(x, 0);
}
function memoize(fn) {
    var results = {};
    return function () {
        var args = toArray(arguments),
            key = JSON.stringify(args)
            result = results[key];
        if (!result) {
            result = results[key] = fn.apply(this, args);
        }
        return result;
    }
}

function once(fn) {
    var one = fn;
    return function() {
        var args = toArray(arguments);
        one.apply(this, args);
        if(one !== noop) {
            one = noop;
        }
    };
}

var noop = function (){};

Function.prototype.debounce = function (delay) {
    return debounce(delay, this);
};

function foo() {
    console.log('foo called')
}

function bar() {
    console.log('bar called');
}

function baz(x) {
  return x + ' - ' + (+new Date());  
};

function wee() {
    console.log('wee called');;
};

var debouncedFoo = foo.debounce(500);
var throttledBar = throttle(500, bar);
var memoBaz = memoize(baz);
var oneWee = once(wee);

var intervalTick = 0;
var interval = setInterval(function () {
    console.log('#', intervalTick);
    debouncedFoo();
    throttledBar();
    console.log('baz:', memoBaz('test'));
    console.log('baz:', memoBaz('test' + intervalTick));
    oneWee();
    console.log('------');
    if (intervalTick++ > 3) {
        clearInterval(interval);
    }
}, 200);