Back to Functions

update

object

This method is like set except that it accepts updater to produce the value to set.

Installation

Import
import { update } from '@tulx/utils';

Source Code

Implementation
/**
 * This method is like set except that it accepts updater to produce the value to set.
 *
 * @param object - The object to modify.
 * @param path - The path of the property to set.
 * @param updater - The function to produce the updated value.
 * @returns Returns object.
 *
 * @example
 * ```ts
 * const object = { 'a': [{ 'b': { 'c': 3 } }] };
 * update(object, 'a[0].b.c', (n) => n * n);
 * console.log(object.a[0].b.c); // 9
 * ```
 */
export function update<T extends Record<string, unknown>>(
  object: T,
  path: string | readonly (string | number)[],
  updater: (value: unknown) => unknown
): T {
  const pathArray = Array.isArray(path)
    ? path.map(String)
    : parsePath(String(path));
  let current: unknown = object;

  for (let i = 0; i < pathArray.length - 1; i++) {
    const key = pathArray[i];
    if (
      current === null ||
      current === undefined ||
      typeof current !== 'object'
    ) {
      return object;
    }
    const currentObj = current as Record<string, unknown>;
    if (
      !(key in currentObj) ||
      typeof currentObj[key] !== 'object' ||
      currentObj[key] === null
    ) {
      currentObj[key] = {};
    }
    current = currentObj[key];
  }

  const lastKey = pathArray[pathArray.length - 1];
  const currentObj = current as Record<string, unknown>;
  const currentValue = currentObj[lastKey];
  currentObj[lastKey] = updater(currentValue);

  return object;
}

function parsePath(path: string): string[] {
  const keys: string[] = [];
  let current = '';
  let inBrackets = false;

  for (let i = 0; i < path.length; i++) {
    const char = path[i];
    if (char === '[') {
      if (current) {
        keys.push(current);
        current = '';
      }
      inBrackets = true;
    } else if (char === ']') {
      if (current) {
        keys.push(current);
        current = '';
      }
      inBrackets = false;
    } else if (char === '.' && !inBrackets) {
      if (current) {
        keys.push(current);
        current = '';
      }
    } else {
      current += char;
    }
  }

  if (current) {
    keys.push(current);
  }

  return keys;
}

Example

import { update } from '@tulx/utils';

const object = { 'a': [{ 'b': { 'c': 3 } }] };
update(object, 'a[0].b.c', (n) => n * n);
console.log(object.a[0].b.c); // 9

Related Functions