-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathmatrixDataGenerator.ts
More file actions
95 lines (83 loc) · 2.46 KB
/
matrixDataGenerator.ts
File metadata and controls
95 lines (83 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { diffDays, parseDate } from "../util/dateUtils";
import { Contribution, ContributionCellData } from "../types";
import { DateTime } from "luxon";
export function generateByData(data: Contribution[]) {
if (!data || data.length === 0) {
return [];
}
const dateData = data.map((item) => {
const localDate = parseDate(item.date);
return {
...item,
date: localDate,
timestamp: localDate.getTime(),
};
});
const sortedData = dateData.sort((a, b) => b.timestamp - a.timestamp);
const min = sortedData[sortedData.length - 1].timestamp;
const max = sortedData[0].timestamp;
return generateByFixedDate(new Date(min), new Date(max), data);
}
export function generateByFixedDate(
from: Date,
to: Date,
data: Contribution[]
) {
const days = diffDays(from, to) + 1;
// convert contributions to map: date(yyyy-MM-dd) -> value(sum)
const contributionMapByDate = contributionToMap(data);
const cellData: ContributionCellData[] = [];
const toDateTime = DateTime.fromJSDate(to);
// fill data
for (let i = 0; i < days; i++) {
const currentDateAtIndex = toDateTime.minus({ days: i });
const isoDate = currentDateAtIndex.toFormat('yyyy-MM-dd');
const contribution = contributionMapByDate.get(isoDate);
cellData.unshift({
date: isoDate,
weekDay: currentDateAtIndex.weekday == 7 ? 0 : currentDateAtIndex.weekday,
month: currentDateAtIndex.month - 1,
monthDate: currentDateAtIndex.day,
year: currentDateAtIndex.year,
value: contribution ? contribution.value : 0,
summary: contribution ? contribution.summary : undefined,
items: contribution ? contribution.items || [] : [],
});
}
return cellData;
}
/**
* - generate two-dimensional matrix data
* - every column is week, from Sunday to Saturday
* - every cell is a day
*/
export function generateByLatestDays(
days: number,
data: Contribution[] = []
): ContributionCellData[] {
const fromDate = new Date();
fromDate.setDate(fromDate.getDate() - days + 1);
return generateByFixedDate(fromDate, new Date(), data);
}
function contributionToMap(data: Contribution[]) {
const map = new Map<string, Contribution>();
for (const item of data) {
let key;
if (typeof item.date === "string") {
key = item.date;
} else {
key = DateTime.fromJSDate(item.date).toFormat('yyyy-MM-dd');
}
if (map.has(key)) {
const newItem = {
...item,
// @ts-ignore
value: map.get(key).value + item.value,
};
map.set(key, newItem);
} else {
map.set(key, item);
}
}
return map;
}