瀏覽代碼

add memoize and removeProp function

mightyplow 7 年之前
父節點
當前提交
6dc419cbe4
共有 6 個文件被更改,包括 45 次插入3 次删除
  1. 1 1
      package.json
  2. 1 0
      src/function/index.js
  3. 30 0
      src/function/memoize.js
  4. 3 1
      src/index.js
  5. 2 1
      src/object/index.js
  6. 8 0
      src/object/removeProp.js

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "@mightyplow/jslib",
-  "version": "0.10.2",
+  "version": "0.11.0",
   "description": "js helpers library",
   "main": "dist/index.js",
   "private": true,

+ 1 - 0
src/function/index.js

@@ -7,5 +7,6 @@ export { default as curry } from './curry';
 export { default as enqueue } from './enqueue';
 export { default as enqueueWithResults } from './enqueueWithResults';
 export { default as identity } from './identity';
+export { default as memoize } from './memoize';
 export { default as noop } from './noop';
 export { default as promisify } from './promisify';

+ 30 - 0
src/function/memoize.js

@@ -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;

+ 3 - 1
src/index.js

@@ -14,6 +14,7 @@ export {
     enqueueWithResults,
     enqueue,
     identity,
+    memoize,
     noop,
     promisify
 } from './function';
@@ -30,7 +31,8 @@ export {
     defaults,
     filter,
     fromArray,
-    prop
+    prop,
+    removeProp
 } from './object';
 
 export {

+ 2 - 1
src/object/index.js

@@ -4,4 +4,5 @@
 export { default as defaults } from './defaults';
 export { default as fromArray } from './fromArray';
 export { default as filter } from './filter';
-export { default as prop } from './prop';
+export { default as prop } from './prop';
+export { default as removeProp } from './removeProp';

+ 8 - 0
src/object/removeProp.js

@@ -0,0 +1,8 @@
+/**
+ * @memberOf object
+ *
+ * @param object
+ */
+const removeProp = (object = {}) => key => delete object[key];
+
+export default removeProp;