Newer
Older
CloudBrainNew / src / utils / index.js
dutingting 5 days ago 1 KB pending

export function deepMerge (target, merged) {
  for (var key in merged) {
    if (target[key] && typeof (target[key]) === 'object') {
      deepMerge(target[key], merged[key])
      continue
    }
    target[key] = merged[key]
  }
  return target
}
// 防抖
export function debounce (delay, callback) {
  let lastTime
  return function () {
    clearTimeout(lastTime)
    const [that, args] = [this, arguments]
    lastTime = setTimeout(() => {
      callback.apply(that, args)
    }, delay)
  }
}

export function observerDomResize (dom, callback) {
  // 监听dom树变化
  const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
  const observer = new MutationObserver(callback)
  observer.observe(dom, { attributes: true, attributeFilter: ['style'], attributeOldValue: true })
  return observer
}

export function deepClone (object) {
  // 是否需要递归
  var recursion = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false
  if (!object) return object
  const parse = JSON.parse
  const stringify = JSON.stringify
  if (!recursion) return parse(stringify(object))
  var clonedObj = object instanceof Array ? [] : {}

  if (object && typeof (object) === 'object') {
    for (var key in object) {
      if (object.hasOwnProperty(key)) {
        if (object[key] && typeof (object[key]) === 'object') {
          clonedObj[key] = deepClone(object[key], true)
        } else {
          clonedObj[key] = object[key]
        }
      }
    }
  }
  return clonedObj
}

export function formatDateDefault (timeString) {
  const date = new Date(timeString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}