memoize.js

July 02, 2021

Ensures that the given function can only be called a single time.

  • Subsequent calls will return the return value of the first call.
/**
 * Ensures that the given function can only be called a single time.
 * Subsequent calls will return the return value of the first call.
 * 
 * (c) 2021 Onur Boz, Boz, MIT License, https://onurboz.com/mit
 * 
 * @note Note that this is a simple implementation that 
 * doesn't distinguish between argument lists.
 * 
 * @param {Function()}  func  Callback function
 */
function memoize (func) {
  var cached, cache, slice;

  slice = [].slice;
  cache = void 0;
  cached = false;

  return function () {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];

    if (cached) {
      return cache;
    } else {
      cached = true;
      return cache = func.apply(null, args);
    }
  };

};