UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions and classes for everyday development needs.

44 lines (43 loc) 1.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports._resolveNestedKey = _resolveNestedKey; exports._getNumericProp = _getNumericProp; const non_primitives_1 = require("../guards/non-primitives"); const utilities_1 = require("../number/utilities"); /** * Safely resolves nested keys from a dot-separated string like "user.city". * * @param obj - The source object * @param path - The nested path string (e.g. "user.city") * @returns The resolved value or `undefined` */ function _resolveNestedKey(obj, path) { if ((0, non_primitives_1.isNotEmptyObject)(obj)) { return path?.split('.').reduce((acc, key) => { if ((0, non_primitives_1.isNotEmptyObject)(acc)) { return acc[key]; } }, obj); } } /** * Retrieves a numeric value from a nested property in dot notation. * Falls back to 0 if value is not a number or numeric string. * * @param obj - The source object to read from. * @param path - The path string like 'user.income.tax'. * @returns The numeric value at that path, or 0 if not valid. */ function _getNumericProp(obj, path) { if ((0, non_primitives_1.isNotEmptyObject)(obj)) { const value = path?.split('.').reduce((acc, key) => { if ((0, non_primitives_1.isNotEmptyObject)(acc)) { return acc[key]; } }, obj); return (0, utilities_1.normalizeNumber)(value) ?? 0; } else { return 0; } }