Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. /**
  2. * Create new object with props from both `source` and `changes` objects.
  3. *
  4. * @param {Object} source Source object.
  5. * @param {Object} changes Object, which props overrides source's props.
  6. * @param {number} [mergeThreshold=100] Maximum count of source's own props,
  7. * after which source object will be merged with it's prototype.
  8. *
  9. * @returns {Object} New object with props from both `source` and `changes`.
  10. */
  11. export default function protoMerge(source, changes, mergeThreshold = 100) {
  12. let result;
  13. const proto = Object.getPrototypeOf(source);
  14.  
  15. if (proto === Object.prototype || proto == null) {
  16. // if source is plain object - inherit result from source
  17. result = Object.create(source);
  18. } else {
  19. const sourceKeys = Object.keys(source);
  20. const sourceLength = sourceKeys.length;
  21.  
  22. if (sourceLength < mergethreshold) {
  23. result = Object.create(proto);
  24. // if source size less than threshold - copy source's own props
  25. for (let i = 0; i < sourceLength; i++) {
  26. const key = sourceKeys[i]
  27. result[key] = source[key];
  28. }
  29. } else {
  30. result = {};
  31. // else - copy all enumerable props from source and it's prototype
  32. for (const key in source) {
  33. const value = source[key];
  34. if (typeof value !== "undefined") {
  35. result[key] = value;
  36. }
  37. }
  38. }
  39. }
  40. // copy all enumerable props from changes object
  41. for (const key in changes) {
  42. result[key] = changes[key];
  43. }
  44. return result;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement