| 1 | import { get } from './get.mjs';
|
|---|
| 2 | import { isUnsafeProperty } from '../../_internal/isUnsafeProperty.mjs';
|
|---|
| 3 | import { assignValue } from '../_internal/assignValue.mjs';
|
|---|
| 4 | import { isIndex } from '../_internal/isIndex.mjs';
|
|---|
| 5 | import { isKey } from '../_internal/isKey.mjs';
|
|---|
| 6 | import { toKey } from '../_internal/toKey.mjs';
|
|---|
| 7 | import { isObject } from '../predicate/isObject.mjs';
|
|---|
| 8 | import { toPath } from '../util/toPath.mjs';
|
|---|
| 9 |
|
|---|
| 10 | function updateWith(obj, path, updater, customizer) {
|
|---|
| 11 | if (obj == null && !isObject(obj)) {
|
|---|
| 12 | return obj;
|
|---|
| 13 | }
|
|---|
| 14 | let resolvedPath;
|
|---|
| 15 | if (isKey(path, obj)) {
|
|---|
| 16 | resolvedPath = [path];
|
|---|
| 17 | }
|
|---|
| 18 | else if (Array.isArray(path)) {
|
|---|
| 19 | resolvedPath = path;
|
|---|
| 20 | }
|
|---|
| 21 | else {
|
|---|
| 22 | resolvedPath = toPath(path);
|
|---|
| 23 | }
|
|---|
| 24 | const updateValue = updater(get(obj, resolvedPath));
|
|---|
| 25 | let current = obj;
|
|---|
| 26 | for (let i = 0; i < resolvedPath.length && current != null; i++) {
|
|---|
| 27 | const key = toKey(resolvedPath[i]);
|
|---|
| 28 | if (isUnsafeProperty(key)) {
|
|---|
| 29 | continue;
|
|---|
| 30 | }
|
|---|
| 31 | let newValue;
|
|---|
| 32 | if (i === resolvedPath.length - 1) {
|
|---|
| 33 | newValue = updateValue;
|
|---|
| 34 | }
|
|---|
| 35 | else {
|
|---|
| 36 | const objValue = current[key];
|
|---|
| 37 | const customizerResult = customizer?.(objValue, key, obj);
|
|---|
| 38 | newValue =
|
|---|
| 39 | customizerResult !== undefined
|
|---|
| 40 | ? customizerResult
|
|---|
| 41 | : isObject(objValue)
|
|---|
| 42 | ? objValue
|
|---|
| 43 | : isIndex(resolvedPath[i + 1])
|
|---|
| 44 | ? []
|
|---|
| 45 | : {};
|
|---|
| 46 | }
|
|---|
| 47 | assignValue(current, key, newValue);
|
|---|
| 48 | current = current[key];
|
|---|
| 49 | }
|
|---|
| 50 | return obj;
|
|---|
| 51 | }
|
|---|
| 52 |
|
|---|
| 53 | export { updateWith };
|
|---|