Repository navigation
Expand file tree
/
Copy pathsession-grouper.js
More file actions
75 lines (63 loc) · 2.13 KB
/
Copy pathsession-grouper.js
File metadata and controls
75 lines (63 loc) · 2.13 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
function groupSessions(sessions, config = {}) {
const now = config.now ? new Date(config.now) : new Date();
const startOfToday = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
const startOfYesterday = startOfToday - 86400000;
const dayOfWeek = now.getUTCDay();
const startOfWeek = startOfToday - (dayOfWeek * 86400000);
const buckets = {
Today: [],
Yesterday: [],
'This Week': []
};
for (const session of sessions) {
const modified = new Date(session.modified);
const startOfModified = Date.UTC(
modified.getUTCFullYear(),
modified.getUTCMonth(),
modified.getUTCDate()
);
if (startOfModified === startOfToday) {
buckets.Today.push(session);
} else if (startOfModified === startOfYesterday) {
buckets.Yesterday.push(session);
} else if (startOfModified >= startOfWeek && startOfModified < startOfYesterday) {
buckets['This Week'].push(session);
} else {
const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
const monthKey = `${monthNames[modified.getUTCMonth()]} ${modified.getUTCFullYear()}`;
if (!buckets[monthKey]) buckets[monthKey] = [];
buckets[monthKey].push(session);
}
}
const defaultExpanded = config.expandedGroups || ['Today', 'Yesterday'];
const result = [];
for (const name of ['Today', 'Yesterday', 'This Week']) {
if (buckets[name] && buckets[name].length > 0) {
result.push({
name,
expanded: defaultExpanded.includes(name),
sessions: buckets[name]
});
}
}
const monthKeys = Object.keys(buckets).filter(
k => !['Today', 'Yesterday', 'This Week'].includes(k)
);
monthKeys.sort((a, b) => {
const dateA = new Date(buckets[a][0].modified);
const dateB = new Date(buckets[b][0].modified);
return dateB - dateA;
});
for (const name of monthKeys) {
result.push({
name,
expanded: defaultExpanded.includes(name),
sessions: buckets[name]
});
}
return result;
}
module.exports = { groupSessions };