supple.js 2.67 KB
// 补充数据
// 数据分组
export function groupData(data) {
  let groupObject = {}
  data.forEach(item => {
    groupObject[item.mallId]
      ? groupObject[item.mallId].push(item)
      : groupObject[item.mallId] = [item]
  })
  return groupObject
}

// 计算开始结束时间总天数
export function caleCountDay(startDate, endDate) {
  let s_stamp = (
    typeof(startDate) === 'string'
      ? new Date(startDate.replace(/-/g, '/'))
      : new Date(startDate)
  ).getTime()
  let e_stamp = (
    typeof(startDate) === 'string'
      ? new Date(endDate.replace(/-/g, '/'))
      : new Date(endDate)
  ).getTime()
  let dateObj = {}
  Array.from(
    { length: (e_stamp - s_stamp) / (24 * 60 * 60 * 1000) + 1 },
    (v, k) => s_stamp + (k * 24 * 60 * 60 * 1000)
  ).forEach(item => {
    dateObj[item] = null
  })
  return dateObj
}

// 格式化年月日时分秒
export function formatStamp(stamp) {
  let time = new Date(stamp)
  return [
    [
      time.getFullYear(),
      time.getMonth() + 1,
      time.getDate()].join('-'),
      [
        time.getHours(),
        time.getMinutes(),
        time.getSeconds()
      ].join(':')
  ].join(' ').replace(/(?=\b\d\b)/g, '0')
}

/**
 * 补全数据
 * @param {number} currentStamp
 * @param {number} lastStamp
 * @param {object} keyExample
 * @param {string} needKey
 * @returns {array}
 */
export function suppleHandle(stamp, keyExample, needKey = 'countdate') {
  let temp = {}
  Object.keys(keyExample).forEach(key => {
    if (key !== 'mall') {
      temp[key] = '--'
    } else {
      temp[key] = keyExample[key]
    }
    temp[needKey] = formatStamp(stamp)
  })
  return temp
}

/**
 * complate data
 * @param {array} data
 * @param {string} startDate
 * @param {string} endDate
 * @returns {array}
 */
export function complateData(data, startDate, endDate) {
  let resultData = []
  let groups = groupData(data)
  let countDayObj = caleCountDay(startDate, endDate)
  Object.keys(groups).forEach(key => {
    if (groups[key].length < Object.keys(countDayObj).length) {
      let completeData = []
      // 遍历开始结束日期对象, 补全数据
      for (let [k, v] of Object.entries(countDayObj)) {
        let filterExist = groups[key].filter((item, index) => {
          let curStamp =  new Date(item.countdate.split(' ')[0].replace(/-/g, '/')).getTime()
          return curStamp == k
        })
        if (!filterExist.length) {
          countDayObj[k] = suppleHandle(k - 0, groups[key][0])
        } else {
          countDayObj[k] = filterExist[0]
        }
      }
      Object.keys(countDayObj).forEach(k => {
        resultData.push(countDayObj[k])
      })
    } else {
      resultData.push(...groups[key])
    }
  })

  return resultData
}