From 46d1575bff07955a939de605a244aa0ec6a1661c Mon Sep 17 00:00:00 2001 From: shubhamsharma9199 Date: Thu, 6 Nov 2025 05:41:36 +0530 Subject: [PATCH] perf(find-pipe): optimize lookup performance using WeakMap caching and Map.get() --- src/app/pipes/find.pipe.ts | 39 ++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/src/app/pipes/find.pipe.ts b/src/app/pipes/find.pipe.ts index 81d35d879..df034ba28 100644 --- a/src/app/pipes/find.pipe.ts +++ b/src/app/pipes/find.pipe.ts @@ -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>> + */ +const lookupCache = new WeakMap>>(); + @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>(); + 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(); + 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] ?? '') : ''; } }