准备工作
String.prototype._padStart = function (maxLen, fillStr) {
return this.length < maxLen ? this.padStart(maxLen, fillStr) : this.toString()
}
const utilObj = {
date: new Date(),
year () {
return this.date.getFullYear()
},
month () {
return this.date.getMonth() + 1
},
day () {
return this.date.getDate()
},
toMs (days) {
return days * 24 * 60 * 60 * 1000
},
toTimeStamp (dateStr) {
return new Date(dateStr).getTime()
},
prevYear () {
let y = this.year()
y = y - 1
return [`${y}-01-01`, `${y}-12-31`]
},
currentYear () {
const y = this.year()
return [`${y}-01-01`, `${y}-${this.month()}-${this.day()}`]
},
pastDays (days) {
const end = this.date.getTime()
const start = end - this.toMs(days - 1)
return [
this.format(new Date(start)),
this.format(new Date(end))
]
},
format (date, format = 'YYYY-mm-dd') {
const obj = {
"YYYY": date.getFullYear().toString(),
"mm": (date.getMonth() + 1).toString()._padStart(2, '0'),
"dd": date.getDate().toString()._padStart(2, '0'),
"HH": date.getHours().toString()._padStart(2, '0'),
"MM": date.getMinutes().toString()._padStart(2, '0'),
"SS": date.getSeconds().toString()._padStart(2, '0')
};
for (let k in obj) {
format = format.replace(k, obj[k])
};
return format;
}
}
实现 MakeXDataMap 类
class MakeXDataMap {
constructor () {
this.xData = []
if (arguments.length === 1) {
if (Array.isArray(arguments[0])) {
this.xData = arguments[0]
} else {
this.xData = this.getXData(...this.getDateRangeByDateType(arguments[0]))
}
}
if (arguments.length === 2) {
this.xData = this.getXData(...arguments)
}
}
getDateRangeByDateType (dateType) {
switch (dateType) {
case 0:
return utilObj.prevYear()
case 1:
return utilObj.currentYear()
case 2:
return utilObj.pastDays(180)
case 3:
return utilObj.pastDays(90)
case 4:
return utilObj.pastDays(30)
case 5:
return utilObj.pastDays(7)
}
}
getXData (startDate, endDate) {
const xData = []
startDate = new Date(startDate).getTime()
endDate = new Date(endDate).getTime()
while (startDate <= endDate) {
xData.push(utilObj.format(new Date(startDate)))
startDate = startDate + 24 * 60 * 60 * 1000
}
return xData
}
getXDataMap () {
const map = new Map()
this.xData.forEach(x => {
map.set(x, 0)
})
return map
}
}
测试
const obj = new MakeXDataMap(5)
console.log(obj.xData)
const map = obj.getXDataMap()
const data = [
{ date: '2022-05-28', value: '4' },
{ date: '2022-05-30', value: '8' },
]
data.forEach(item => {
map.set(item.date, item.value)
})
const xData = obj.xData
const yData = [...map.values()]
console.log(xData)
console.log(yData)