object.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const hasOwnPropMethod = {}.hasOwnProperty
  2. export function assignTo(target, ...sources) {
  3. for (let i = 0; i < sources.length; i++) {
  4. let source = sources[i]
  5. if (source != null) { // skip over if undefined or null
  6. for (let key in source) {
  7. // avoid bugs when hasOwnProperty is shadowed
  8. if (Object.prototype.hasOwnProperty.call(source, key)) {
  9. target[key] = source[key]
  10. }
  11. }
  12. }
  13. }
  14. return target
  15. }
  16. export function isEmptyObject(obj) {
  17. for (let _key in obj) {
  18. return false
  19. }
  20. return true
  21. }
  22. export function copyOwnProps(src, dest) {
  23. for (let name in src) {
  24. if (hasOwnProp(src, name)) {
  25. dest[name] = src[name]
  26. }
  27. }
  28. }
  29. function hasOwnProp(obj, name) {
  30. return hasOwnPropMethod.call(obj, name)
  31. }
  32. // Merges an array of objects into a single object.
  33. // The second argument allows for an array of property names who's object values will be merged together.
  34. export function mergeProps(propObjs, complexProps?) {
  35. let dest = {}
  36. let i
  37. let name
  38. let complexObjs
  39. let j
  40. let val
  41. let props
  42. if (complexProps) {
  43. for (i = 0; i < complexProps.length; i++) {
  44. name = complexProps[i]
  45. complexObjs = []
  46. // collect the trailing object values, stopping when a non-object is discovered
  47. for (j = propObjs.length - 1; j >= 0; j--) {
  48. val = propObjs[j][name]
  49. if (typeof val === 'object' && val) { // non-null object
  50. complexObjs.unshift(val)
  51. } else if (val !== undefined) {
  52. dest[name] = val // if there were no objects, this value will be used
  53. break
  54. }
  55. }
  56. // if the trailing values were objects, use the merged value
  57. if (complexObjs.length) {
  58. dest[name] = mergeProps(complexObjs)
  59. }
  60. }
  61. }
  62. // copy values into the destination, going from last to first
  63. for (i = propObjs.length - 1; i >= 0; i--) {
  64. props = propObjs[i]
  65. for (name in props) {
  66. if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
  67. dest[name] = props[name]
  68. }
  69. }
  70. }
  71. return dest
  72. }