Memoize Limit

by ronilan

JavaScript

// memoize Limiter

function request(str) {
  console.log('Make AJAX call for', str);
  return ['ajax', 'payload', 'for', str];
}

function memoizeLimit(fn, rate) {
  let cached = null;
  let response;

  let limiter = setTimeout(function() {
    cached = null;
  }, rate)

  result = function(send) {
    if (cached !== send) {
      cached = send;
      response = fn(send);
    }
    return response;
  }

  return result;
}


var action = memoizeLimit(request, 1000);

//

console.log(action('abc'))
console.log(action('abc'))
console.log(action('efg'))

setTimeout(function() {
  console.log(action('efg'))
}, 900)

setTimeout(function() {
  console.log(action('efg'))
}, 1100)