8
0

_baseSet.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import assignValue from './_assignValue';
  2. import castPath from './_castPath';
  3. import isIndex from './_isIndex';
  4. import isKey from './_isKey';
  5. import isObject from './isObject';
  6. import toKey from './_toKey';
  7. /**
  8. * The base implementation of `_.set`.
  9. *
  10. * @private
  11. * @param {Object} object The object to query.
  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. path = isKey(path, object) ? [path] : castPath(path);
  19. var index = -1,
  20. length = path.length,
  21. lastIndex = length - 1,
  22. nested = object;
  23. while (nested != null && ++index < length) {
  24. var key = toKey(path[index]);
  25. if (isObject(nested)) {
  26. var newValue = value;
  27. if (index != lastIndex) {
  28. var objValue = nested[key];
  29. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  30. if (newValue === undefined) {
  31. newValue = objValue == null
  32. ? (isIndex(path[index + 1]) ? [] : {})
  33. : objValue;
  34. }
  35. }
  36. assignValue(nested, key, newValue);
  37. }
  38. nested = nested[key];
  39. }
  40. return object;
  41. }
  42. export default baseSet;