UNPKG

@tmlmobilidade/utils

Version:

A collection of utility functions and helpers for the TML Mobilidade Go monorepo, providing common functionality for batching operations, caching, HTTP requests, object manipulation, permissions, and more.

42 lines (41 loc) 1.57 kB
/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Utility function that returns the value at a given path in an object. * @param obj The object to retrieve the value from. * @param path The path to the value in the object. * @returns The value at the given path or undefined if the path is invalid. */ export function getValueAtPath(obj, path) { if (!path) return undefined; const pathArray = path.match(/([^[.\]])+/g); return pathArray.reduce((prevObj, key) => prevObj && prevObj[key], obj); } /** * Sets a value at a specified dot-separated path within an object. * If intermediate objects or arrays do not exist, they are created. * @param obj The object to set the value in. * @param path The dot-separated path where the value should be set. * @param value The value to set at the specified path. * @returns The updated object with the value set at the specified path. */ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']); export function setValueAtPath(obj, path, value) { const keys = path.split('.'); for (const key of keys) { if (UNSAFE_KEYS.has(key)) { throw new Error(`Unsafe path segment: "${key}"`); } } let current = obj; keys.slice(0, -1).forEach((key) => { if (!(key in current)) { // If numeric key, initialize as array current[key] = /^\d+$/.test(key) ? [] : {}; } current = current[key]; }); const lastKey = keys[keys.length - 1]; current[lastKey] = value; return obj; }