Adds cache helper function.
This commit is contained in:
31
data-extraction/src/js/helpers/cache.ts
Normal file
31
data-extraction/src/js/helpers/cache.ts
Normal 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;
|
||||
}
|
||||
@@ -2,3 +2,4 @@ export * from "./createGraph";
|
||||
export * from "./createGraphFromPointers";
|
||||
export * from "./tryEval";
|
||||
export * from "./markedGrid";
|
||||
export * from "./cache";
|
||||
|
||||
Reference in New Issue
Block a user