baseSet.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // @ts-nocheck
  2. import assignValue from "./assignValue.js";
  3. import castPath from "./castPath.js";
  4. import isIndex from "./isIndex.js";
  5. import isObject from "./isObject.js";
  6. import toKey from "./toKey.js";
  7. /**
  8. * The base implementation of `set`.
  9. *
  10. * @private
  11. * @param {Object} object The object to modify.
  12. * @param {Array|string} path The path of the property to set.
  13. * @param {*} value The value to set.
  14. * @param {Function} [customizer] The function to customize path creation.
  15. * @returns {Object} Returns `object`.
  16. */
  17. function baseSet(object, path, value, customizer) {
  18. if (!isObject(object)) {
  19. return object;
  20. }
  21. path = castPath(path, object);
  22. const length = path.length;
  23. const lastIndex = length - 1;
  24. let index = -1;
  25. let nested = object;
  26. while (nested != null && ++index < length) {
  27. const key = toKey(path[index]);
  28. let newValue = value;
  29. if (index !== lastIndex) {
  30. const objValue = nested[key];
  31. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  32. if (newValue === undefined) {
  33. newValue = isObject(objValue)
  34. ? objValue
  35. : isIndex(path[index + 1])
  36. ? []
  37. : {};
  38. }
  39. }
  40. assignValue(nested, key, newValue);
  41. nested = nested[key];
  42. }
  43. return object;
  44. }
  45. export default baseSet;