_set.js 895 B

1234567891011121314151617181920212223242526
  1. /**
  2. * lodash set
  3. * @param {*} obj
  4. * @param {*} path
  5. * @param {*} value
  6. * @returns
  7. */
  8. function _set(obj, path, value) {
  9. if (Object(obj) !== obj) return obj // When obj is not an object
  10. // If not yet an array, get the keys from the string-path
  11. if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || []
  12. path.slice(0, -1).reduce((a, c, i) => // Iterate all of them except the last one
  13. Object(a[c]) === a[c] // Does the key exist and is its value an object?
  14. // Yes: then follow that path
  15. ?
  16. a[c]
  17. // No: create the key. Is the next key a potential array-index?
  18. :
  19. a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] // Yes: assign a new array object
  20. :
  21. {}, // No: assign a new plain object
  22. obj)[path[path.length - 1]] = value // Finally assign the value to the last key
  23. return obj // Return the top-level object to allow chaining
  24. }
  25. export default _set