Adds cache helper function.

This commit is contained in:
Henning Dieterichs
2020-03-29 18:24:11 +02:00
parent 42e58ce9cf
commit f8daa18170
2 changed files with 32 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
import { DataExtractorApiImpl } from "../api";
const cached = new Map<string, any>();
/**
* Evaluates an expression
*/
export function cache<T>(
expression: string | (() => T),
id: string | number | undefined = undefined
): T {
let resultFn: () => any;
let key: string;
if (typeof expression === "string") {
const evalFn = DataExtractorApiImpl.lastEvalFn!;
resultFn = () => evalFn(expression);
key = JSON.stringify({ expr: expression, id });
} else {
resultFn = () => expression();
key = JSON.stringify({ expr: expression.toString(), id });
}
if (cached.has(key)) {
return cached.get(key);
}
const result = resultFn();
cached.set(key, result);
return result;
}

View File

@@ -2,3 +2,4 @@ export * from "./createGraph";
export * from "./createGraphFromPointers";
export * from "./tryEval";
export * from "./markedGrid";
export * from "./cache";