|
@@ -0,0 +1,30 @@
|
|
|
+import removeProp from '../object/removeProp';
|
|
|
+
|
|
|
+/**
|
|
|
+ * Caches a function result for a specified time.
|
|
|
+ *
|
|
|
+ * @memberOf function
|
|
|
+ *
|
|
|
+ * @param {function} fn - the function of which the result should be cached
|
|
|
+ * @param {number} [timeout] - the time in ms which tells the time after which the results should be deleted from the cache
|
|
|
+ * @returns {function(...[*]=)}
|
|
|
+ */
|
|
|
+const memoize = (fn, timeout) => {
|
|
|
+ const cache = {};
|
|
|
+ const removeCachedValue = key => () => removeProp(cache)(key);
|
|
|
+
|
|
|
+ return (...args) => {
|
|
|
+ const key = JSON.stringify(args || []);
|
|
|
+
|
|
|
+ if (!(key in cache)) {
|
|
|
+ cache[key] = fn(...args);
|
|
|
+
|
|
|
+ // clear cached value after timeout
|
|
|
+ !isNaN(timeout) && setTimeout(removeCachedValue(key), timeout);
|
|
|
+ }
|
|
|
+
|
|
|
+ return cache[key];
|
|
|
+ };
|
|
|
+};
|
|
|
+
|
|
|
+export default memoize;
|