perf(find-pipe): optimize lookup performance using WeakMap caching and Map.get()

This commit is contained in:
shubhamsharma9199
2025-11-06 05:41:36 +05:30
parent b6f43a8467
commit 46d1575bff
+35 -4
View File
@@ -1,12 +1,43 @@
import { Pipe, PipeTransform } from '@angular/core';
/**
* Cache for storing lookup maps per options array reference.
* Uses WeakMap to allow garbage collection when options arrays are no longer referenced.
* Structure: WeakMap<optionsArray, Map<lookupKey, Map<lookupValue, optionObject>>>
*/
const lookupCache = new WeakMap<any[], Map<string, Map<any, any>>>();
@Pipe({ name: 'find' })
export class FindPipe implements PipeTransform {
transform(value: any, options: any, key: string, property: string): any {
let optionFound;
if (options) {
optionFound = options.find((option: any) => option[key] === value);
if (!options || !key || value === null || value === undefined) {
return '';
}
return optionFound ? optionFound[property] : '';
// Get or create the cache for this options array
let keyMap = lookupCache.get(options);
if (!keyMap) {
keyMap = new Map<string, Map<any, any>>();
lookupCache.set(options, keyMap);
}
// Get or create the lookup map for this specific key
let valueMap = keyMap.get(key);
if (!valueMap) {
// Build the lookup map: O(n) - but only once per options array + key combination
valueMap = new Map<any, any>();
if (Array.isArray(options)) {
for (const option of options) {
if (option && option[key] !== undefined && option[key] !== null) {
valueMap.set(option[key], option);
}
}
}
keyMap.set(key, valueMap);
}
// O(1) lookup
const optionFound = valueMap.get(value);
return optionFound ? (optionFound[property] ?? '') : '';
}
}