memoize function

Function memoize(
  1. Function func, [
  2. List? args
])

Creates a function that memoizes the result of func.

Implementation

Function memoize(Function func, [List? args]) {
  // a cache of results
  var results = {};
  // return a function for the cache of results
  return () {
    // a String key to save the results cache
    var argsKey = args?[0].toString() ?? '0';
    // execute `func` only if there is no cached value of clumsysquare()
    if (results[argsKey] == null) {
      // store the return value of clumsysquare()
      results[argsKey] = Function.apply(func, args);
    }
    // return the cached results
    return results[argsKey];
  };
}