_modify.js 926 B

12345678910111213141516171819202122232425262728293031
  1. import _isArray from "./_isArray.js";
  2. import _isInteger from "./_isInteger.js";
  3. /**
  4. * Makes a shallow clone of an object, applying the given fn to the specified
  5. * property with the given value. Note that this copies and flattens prototype
  6. * properties onto the new object as well. All non-primitive properties are
  7. * copied by reference.
  8. *
  9. * @private
  10. * @param {String|Number} prop The property name to set
  11. * @param {Function} fn The function to apply to the property
  12. * @param {Object|Array} obj The object to clone
  13. * @return {Object|Array} A new object equivalent to the original except for the changed property.
  14. */
  15. export default function _modify(prop, fn, obj) {
  16. if (_isInteger(prop) && _isArray(obj)) {
  17. var arr = [].concat(obj);
  18. arr[prop] = fn(arr[prop]);
  19. return arr;
  20. }
  21. var result = {};
  22. for (var p in obj) {
  23. result[p] = obj[p];
  24. }
  25. result[prop] = fn(result[prop]);
  26. return result;
  27. }