笔记:「饭否精选·日历」微信小程序制作记录 - 微信小程序开发中遇到的问题 - 5
// 日历实现中,对于 date 的 group 和 sort
// Group date by year, then by momth
// sort method here help make an array contian calandar object
// order by the :
// first year: 2017, 2016, 2015
// then monthe: 12, 11, 10, 9, 8, 7, 6, ... , 3, 2, 1
// then daY: 1, 2, 3, 4, 5, ... , 30, 31
sort(dates) {
// _sort:
// first level of date obj is:
// {2015: {month: {...}}, 2016: {month: {...}}, 2017: {month: {...}}}
// shoule be push into calendar array in order:
// [2017.12, 2017.11, 2017.10, ..., 2017.1, 2016.12, 2016.11 ...]
const _sort = (dateObj) => Object.keys(dateObj).sort((a, b) => b - a);
return _sort(dates).reduce((yearArr, year) => {
return _sort(dates[year]).reduce((monthObj, month) => {
yearArr.push(this.make(year, month, dates[year][month]));
return yearArr;
}, {});
}, []);
}
// turn Array: [2015-01-01, 2016-02-02, 2017-03-03]
// to Object: { 2015: {01: [2015-01-01]}, 2016: { 02: [2016-02-02] }. { 2017: { 03: [2017-03-03] } }}
//
groupDate(dates) {
return new Promise((resolve, reject) => {
resolve(dates.reduce((l, r) => {
// 2017-01-01 => [2017, 01, 01]
let date = r.split('-').map(s => parseInt(s))
// date[0] => year: 2017, date[1] => month: 1. date[2] => day: 1
if (typeof l[date[0]] === 'undefined') l[date[0]] = {}
if (typeof l[date[0]][date[1]] === 'undefined') l[date[0]][date[1]] = []
l[date[0]][date[1]].push(r)
return l;
}, {}))
})
}