defaults.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var baseRest = require('./_baseRest'),
  2. eq = require('./eq'),
  3. isIterateeCall = require('./_isIterateeCall'),
  4. keysIn = require('./keysIn');
  5. /** Used for built-in method references. */
  6. var objectProto = Object.prototype;
  7. /** Used to check objects for own properties. */
  8. var hasOwnProperty = objectProto.hasOwnProperty;
  9. /**
  10. * Assigns own and inherited enumerable string keyed properties of source
  11. * objects to the destination object for all destination properties that
  12. * resolve to `undefined`. Source objects are applied from left to right.
  13. * Once a property is set, additional values of the same property are ignored.
  14. *
  15. * **Note:** This method mutates `object`.
  16. *
  17. * @static
  18. * @since 0.1.0
  19. * @memberOf _
  20. * @category Object
  21. * @param {Object} object The destination object.
  22. * @param {...Object} [sources] The source objects.
  23. * @returns {Object} Returns `object`.
  24. * @see _.defaultsDeep
  25. * @example
  26. *
  27. * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
  28. * // => { 'a': 1, 'b': 2 }
  29. */
  30. var defaults = baseRest(function(object, sources) {
  31. object = Object(object);
  32. var index = -1;
  33. var length = sources.length;
  34. var guard = length > 2 ? sources[2] : undefined;
  35. if (guard && isIterateeCall(sources[0], sources[1], guard)) {
  36. length = 1;
  37. }
  38. while (++index < length) {
  39. var source = sources[index];
  40. var props = keysIn(source);
  41. var propsIndex = -1;
  42. var propsLength = props.length;
  43. while (++propsIndex < propsLength) {
  44. var key = props[propsIndex];
  45. var value = object[key];
  46. if (value === undefined ||
  47. (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
  48. object[key] = source[key];
  49. }
  50. }
  51. }
  52. return object;
  53. });
  54. module.exports = defaults;