Skip to main content

withCalculationCache

@svenvw/fdm-source


@svenvw/fdm-source / fdm-core/src / withCalculationCache

Function: withCalculationCache()

withCalculationCache<T_Input, T_Output>(calculationFunction, calculationFunctionName, calculatorVersion): (fdm, input) => Promise<T_Output>

Defined in: fdm-core/src/calculator.ts:163

A decorator function that adds caching capabilities to any asynchronous calculation function. It first attempts to retrieve a result from the cache. If a cached result is found, it's returned immediately. If not, the original calculation function is executed, its result is cached (if cache read was successful), and then returned. Errors during calculation are logged and re-thrown.

Type Parameters

T_Input

T_Input extends object

The type of the input object for the calculation function.

T_Output

T_Output

The expected type of the calculation result.

Parameters

calculationFunction

(inputs) => T_Output | Promise<T_Output>

The original function to compute the result.

calculationFunctionName

string

The name of the calculation function, used for caching.

calculatorVersion

string

A version string tied to the current calculation function. Changing this version will invalidate old cache entries.

Returns

A new function that wraps the original calculation with caching logic.

(fdm, input): Promise<T_Output>

Parameters

fdm

any

input

T_Input

Returns

Promise<T_Output>

Example

// Define a calculation function
async function myExpensiveCalculation(data: { value: number }): Promise<number> {
// Simulate an expensive operation
await new Promise(resolve => setTimeout(resolve, 1000));
return data.value * 2;
}

// Decorate it with caching
const cachedCalculation = withCalculationCache(myExpensiveCalculation, 'myExpensiveCalculation', 'v1.0.0');

// Use the decorated function
// Assuming 'fdm' is an initialized FdmType instance
const result1 = await cachedCalculation(fdm, { value: 10 }); // Cache MISS, performs calculation
const result2 = await cachedCalculation(fdm, { value: 10 }); // Cache HIT, returns cached result instantly