index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. var hasOwn = Object.prototype.hasOwnProperty;
  3. var toStr = Object.prototype.toString;
  4. var isArray = function isArray(arr) {
  5. if (typeof Array.isArray === 'function') {
  6. return Array.isArray(arr);
  7. }
  8. return toStr.call(arr) === '[object Array]';
  9. };
  10. var isPlainObject = function isPlainObject(obj) {
  11. if (!obj || toStr.call(obj) !== '[object Object]') {
  12. return false;
  13. }
  14. var hasOwnConstructor = hasOwn.call(obj, 'constructor');
  15. var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
  16. // Not own constructor property must be Object
  17. if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
  18. return false;
  19. }
  20. // Own properties are enumerated firstly, so to speed up,
  21. // if last one is own, then all properties are own.
  22. var key;
  23. for (key in obj) {/**/}
  24. return typeof key === 'undefined' || hasOwn.call(obj, key);
  25. };
  26. module.exports = function extend() {
  27. var options, name, src, copy, copyIsArray, clone,
  28. target = arguments[0],
  29. i = 1,
  30. length = arguments.length,
  31. deep = false;
  32. // Handle a deep copy situation
  33. if (typeof target === 'boolean') {
  34. deep = target;
  35. target = arguments[1] || {};
  36. // skip the boolean and the target
  37. i = 2;
  38. } else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) {
  39. target = {};
  40. }
  41. for (; i < length; ++i) {
  42. options = arguments[i];
  43. // Only deal with non-null/undefined values
  44. if (options != null) {
  45. // Extend the base object
  46. for (name in options) {
  47. src = target[name];
  48. copy = options[name];
  49. // Prevent never-ending loop
  50. if (target !== copy) {
  51. // Recurse if we're merging plain objects or arrays
  52. if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
  53. if (copyIsArray) {
  54. copyIsArray = false;
  55. clone = src && isArray(src) ? src : [];
  56. } else {
  57. clone = src && isPlainObject(src) ? src : {};
  58. }
  59. // Never move original objects, clone them
  60. target[name] = extend(deep, clone, copy);
  61. // Don't bring in undefined values
  62. } else if (typeof copy !== 'undefined') {
  63. target[name] = copy;
  64. }
  65. }
  66. }
  67. }
  68. }
  69. // Return the modified object
  70. return target;
  71. };