问题描述
我有一个异步数据,我正在使用这个函数从 Firebase Firestore 加载
graphDataSubscription;
//dataCounter;
passtotalCalData;
totalCalories;
dates=[];
caloriesData=[];
getGraphDateCalories() {
if(this.graphDataSubscription){
this.graphDataSubscription.unsubscribe()
}
this.graphDataSubscription = this.mealService.grabMealGraphDataCalories(this.startDate,this.gatheredUid.uid).subscribe(items => {
this.dates = []
this.passtotalCalData = []
//this.dataCounter = 0;
this.totalCalories=0;
this.caloriesData=[];
items.forEach( item => {
//this.dataCounter++
var data: any = item.data()
this.passtotalCalData.push(data.calories)
this.caloriesData.push(data);
this.totalCalories += data.calories;
this.dates.push(moment(data.date).locale(window.navigator.language).format("DD MMM"))
})
console.log("data acquired");
this.calendarData = this.getCalendarData();
this.calendarData = [...this.calendarData];
})
}
然后我试图将收集到的值插入到一个对象中,以在需要特定对象格式的图表中显示。这是一个热图图表,因此即使没有每一天的数据,它也必须包括前一年的全部天数。 like in this link
这是我做日期比较的函数,即使异步数据在一秒内收集也需要将近12秒。
calendarData: any[] = [];
getCalendarData(): any[] {
//console.log("begin")
// today
const Now = new Date();
const todaysDay = Now.getDate();
const thisDay = new Date(Now.getFullYear(),Now.getMonth(),todaysDay);
// Monday
const thisMonday = new Date(thisDay.getFullYear(),thisDay.getMonth(),todaysDay - thisDay.getDay() + 1);
const thisMondayDay = thisMonday.getDate();
const thisMondayYear = thisMonday.getFullYear();
const thisMondayMonth = thisMonday.getMonth();
// 52 weeks before monday
const calendarData = [];
const getDate = d => new Date(thisMondayYear,thisMondayMonth,d);
for (let week = -52; week <= 0; week++) {
const mondayDay = thisMondayDay + week * 7;
const monday = getDate(mondayDay);
// one week
const series = [];
for (let dayOfWeek = 7; dayOfWeek > 0; dayOfWeek--) {
const date = getDate(mondayDay - 1 + dayOfWeek);
// skip future dates
if (date > Now) {
continue;
}
// value
var value = 0;
console.log("assigning to the object begins")
this.caloriesData.forEach(data => {
if (data["date"] === date.toLocaleDateString('en-CA')) {
value = data["calories"];
//console.log("condition granted");
return;
}
});
console.log("assigning to the object ends")
series.push({
date,name: weekdayName.format(date),value
});
}
calendarData.push({
name: monday.toString(),series
});
}
return calendarData;
}
我知道这是太多的代码,但我不确定如何针对这个特定问题创建一个最小的示例。 那么有没有办法让这种比较更快呢?
这部分花费了很长时间,我的意思是它在两个嵌套的 for 循环中分别是一个 for each ,但我仍然不明白为什么比较这些日期需要这么多时间
var value = 0;
console.log("assigning to the object begins")
this.caloriesData.forEach(data => {
if (data["date"] === date.toLocaleDateString('en-CA')) {
value = data["calories"];
//console.log("condition granted");
return;
}
});
console.log("assigning to the object ends")
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)