-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (85 loc) · 2.49 KB
/
index.js
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
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek.js';
dayjs.extend(isoWeek);
const formats = {
day: 'YYYY-MM-DD',
month: 'YYYY-MM',
year: 'YYYY',
}
export default class DateSequence {
static createPeriod(period, to, maxUnits = 10) {
const dfrom = dayjs(to).subtract(maxUnits, period);
const from = dfrom.format('YYYY-MM-DD');
if(period !== 'week') {
return DateSequence.units(
from, to,
dfrom, maxUnits,
period, formats[period],
);
}
return DateSequence.weekUnits(from, to, dfrom, maxUnits);
}
static create(from, to, maxUnits = 10) {
const dfrom = dayjs(from);
const days = dayjs(to).diff(dfrom, 'day') + 1;
if(days <= maxUnits) {
return DateSequence.units(
from, to,
dfrom, days,
'day', 'YYYY-MM-DD'
);
}
const weeks = dayjs(to).diff(dfrom, 'week');
if(weeks <= maxUnits) {
return DateSequence.weekUnits(from, to, dfrom, weeks);
}
const months = dayjs(to).diff(dfrom, 'month');
if(months <= maxUnits) {
return DateSequence.units(
from, to,
dfrom, months,
'month', 'YYYY-MM'
);
}
const years = dayjs(to).diff(dfrom, 'year');
return DateSequence.units(
from, to,
dfrom, Math.min(years,maxUnits),
'year', 'YYYY'
);
}
static weekUnits(from, to, dfrom, weeks) {
const buckets = [];
for(let i=0; i<weeks; i++) {
let dto = dfrom.add(1, 'week');
buckets.push({
label: 'week '+ dfrom.isoWeek(),
from: dfrom.format('YYYY-MM-DD'),
to: dto.format('YYYY-MM-DD'),
});
dfrom = dto;
}
return {
unit: 'week',
buckets,
from, to,
}
}
static units(from, to, dfrom, count, unit, labelFormat) {
const buckets = [];
for(let i=0; i<count; i++) {
let dto = dfrom.add(1, unit);
buckets.push({
label: dfrom.format(labelFormat),
from: dfrom.format('YYYY-MM-DD'),
to: dto.format('YYYY-MM-DD'),
});
dfrom = dto;
}
return {
unit,
buckets,
from, to,
}
}
}