Files
openobserve/web/src/utils/dashboard/aliasUtils.ts
T
2026-07-24 07:11:39 +00:00

50 lines
2.3 KiB
TypeScript

// Copyright 2026 OpenObserve Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/**
* Retrieves a value from an object using a case-insensitive fallback strategy.
*
* Performance-critical: may be called millions of times in nested loops.
* Handles numeric keys, camelCase vs lowercase string keys, falsy values
* (0, false, '', null) which are valid and returned as-is, and null/undefined
* objects/aliases (returns undefined without throwing).
*
* Search strategy: exact (case-sensitive) match first; if not found and alias
* is a string, falls back to its lowercase form. Uses strict inequality (!==)
* so falsy values like 0 and false are returned rather than treated as missing.
*
* @param obj - The object to search in (can be null/undefined)
* @param alias - The key to search for (string or number, can be null/undefined)
* @returns The value if found, undefined otherwise (never throws errors)
*
* @example
* getDataValue({ xAxis: 'time' }, 'xAxis') // Returns 'time'
* getDataValue({ xaxis: 'time' }, 'xAxis') // Returns 'time' (lowercase fallback)
* getDataValue({ 100: 25.5 }, 100) // Returns 25.5
* getDataValue({ count: 0 }, 'count') // Returns 0 (not undefined)
* getDataValue({ flag: false }, 'flag') // Returns false (not undefined)
* getDataValue(null, 'key') // Returns undefined (no error)
* getDataValue({ key: 'value' }, null) // Returns undefined (no error)
*/
export const getDataValue = (obj: any, alias: string | number): any => {
if (!obj || alias == null) return undefined;
const value = obj[alias];
if (value !== undefined) return value;
// Lowercase fallback only for string keys; numeric keys don't need it.
return typeof alias === "string" ? obj[alias.toLowerCase()] : undefined;
};