All files / roosterjs-content-model-dom/lib/domUtils/event cacheGetEventData.ts

100% Statements 5/5
100% Branches 6/6
100% Functions 1/1
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24                  1x           92x     92x 92x   92x    
import type { PluginEvent } from 'roosterjs-content-model-types';
 
/**
 * Gets the cached event data by cache key from event object if there is already one.
 * Otherwise, call getter function to create one, and cache it.
 * @param event The event object
 * @param key Cache key string, need to be unique
 * @param getter Getter function to get the object when it is not in cache yet
 */
export function cacheGetEventData<T, E extends PluginEvent>(
    event: E,
    key: string,
    getter: (event: E) => T
): T {
    const result =
        event.eventDataCache && event.eventDataCache.hasOwnProperty(key)
            ? <T>event.eventDataCache[key]
            : getter(event);
    event.eventDataCache = event.eventDataCache || {};
    event.eventDataCache[key] = result;
 
    return result;
}