@express.ts/cache
Advanced tools
| import { Test } from "./Test"; | ||
| const testInstance = new Test(); | ||
| let cachedValue: any; | ||
| describe("@Cache: getTime & getTimeWithCache returns", () => { | ||
| const shouldBeEqual = () => { | ||
| const time = Date.now(); | ||
| const [ time1, time2 ] = [ | ||
| testInstance.getTime(time), | ||
| testInstance.getTimeWithCache(time) | ||
| ]; | ||
| console.log([ time1, time2 ]); | ||
| expect(time1).toEqual(time2); | ||
| cachedValue = time2; | ||
| }; | ||
| it("should be equal at the beginning", shouldBeEqual); | ||
| it("should be equal after clearing the cache", () => { | ||
| setTimeout(shouldBeEqual, 1001) | ||
| }); | ||
| it("should be equal before clearing the cache", () => { | ||
| setTimeout(shouldBeEqual, 500) | ||
| }); | ||
| }); |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| const keyFactory = (args) => args.reduce((result, currentValue) => `${result},${JSON.stringify(currentValue)}`, ''); | ||
| function Cache(duration) { | ||
| return (target, propertyKey, descriptor) => { | ||
| const value = descriptor.value; | ||
| let cachedValue; | ||
| let cachedValues = {}; | ||
| let timeout; | ||
@@ -11,10 +12,12 @@ descriptor.value = function (...args) { | ||
| throw new Error('Cache timeout must be a positive number'); | ||
| const key = `[${keyFactory(args)}]`; | ||
| const cachedValue = cachedValues[key]; | ||
| if (cachedValue !== undefined) | ||
| return cachedValue; | ||
| cachedValue = value.apply(this, args); | ||
| timeout = setTimeout(() => { | ||
| cachedValue = undefined; | ||
| cachedValues[key] = value.apply(this, args); | ||
| timeout = (setTimeout(() => { | ||
| delete cachedValues[key]; | ||
| clearTimeout(timeout); | ||
| }, duration); | ||
| return cachedValue; | ||
| }, duration)); | ||
| return cachedValues[key]; | ||
| }; | ||
@@ -21,0 +24,0 @@ }; |
+1
-1
| { | ||
| "name": "@express.ts/cache", | ||
| "version": "1.0.0", | ||
| "version": "1.0.1", | ||
| "description": "test package", | ||
@@ -5,0 +5,0 @@ "main": "dist/index", |
+0
-10
@@ -6,12 +6,2 @@ import { Test } from "./Test"; | ||
| console.log([ | ||
| testInstance.getExecutionTime(), | ||
| testInstance.getExecutionTimeWithCache() | ||
| ]); | ||
| console.log([ | ||
| testInstance.getExecutionTime(), | ||
| testInstance.getExecutionTimeWithCache() | ||
| ]); | ||
| describe("@Cache: getExecutionTime & getExecutionTimeWithCache returns", () => { | ||
@@ -18,0 +8,0 @@ |
+9
-0
@@ -17,2 +17,11 @@ | ||
| getTime (duration: number) { | ||
| return this.value + duration; | ||
| } | ||
| @Cache(1000) | ||
| getTimeWithCache (duration: number) { | ||
| return this.value + duration; | ||
| } | ||
| } |
133446
0.68%16
6.67%219
12.31%