Merge pull request #2781 from shubhamkumar9199/optimize/find-pipe-performance
WEB-417: optimize find-pipe performance with caching mechanism
This commit is contained in:
@@ -1,12 +1,43 @@
|
|||||||
import { Pipe, PipeTransform } from '@angular/core';
|
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' })
|
@Pipe({ name: 'find' })
|
||||||
export class FindPipe implements PipeTransform {
|
export class FindPipe implements PipeTransform {
|
||||||
transform(value: any, options: any, key: string, property: string): any {
|
transform(value: any, options: any, key: string, property: string): any {
|
||||||
let optionFound;
|
if (!options || !key || value === null || value === undefined) {
|
||||||
if (options) {
|
return '';
|
||||||
optionFound = options.find((option: any) => option[key] === value);
|
|
||||||
}
|
}
|
||||||
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] ?? '') : '';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user