aboutsummaryrefslogtreecommitdiff
path: root/static/month.js
blob: 05037d4175ecdb6eafc2e1960fcf9cafe46b4a51 (plain)
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
export default class Month {
	constructor(month, year) {
		this.month = month;
		this.year = year;
	}

	next(n) {
		n = n ?? 1;

		const month = this.month + n - 1;
		this.month = (month % 12) + 1;
		this.year += Math.floor(month / 12);

		return this;
	}

	previous(n) {
		n = n ?? 1;

		let month = this.month - n - 1;

		if (month < 0) {
			month += 12;
		}

		this.month = (month % 12) + 1;
		this.year += Math.floor(month / 12);

		return this;
	}

	to(other) {
		const inner = [];
		const current = this.copy();

		while (current.is_same(other) || current.is_before(other)) {
			inner.push(current.copy());
			current.next();
		}

		return inner;
	}

	copy() {
		return new Month(this.month, this.year);
	}

	is_before(other) {
		return this.year < other.year || (this.year == other.year && this.month < other.month);
	}

	is_after(other) {
		return this.year > other.year || (this.year == other.year && this.month > other.month);
	}

	is_same(other) {
		return this.year == other?.year && this.month == other?.month;
	}

	is_same_year(other) {
		return this.year == other.year;
	}

	get name() {
		const date = new Date();
		date.setMonth(this.month - 1);
		return date.toLocaleDateString('default', { month: 'long' })
	}

	static from_unix(date) {
		if (date == null) return null;

		return Month.from_date(new Date(date * 1000));
	}

	static from_date(date) {
		return new Month(date.getMonth() + 1, date.getFullYear());
	}

	static from_string(string) {
		const [ year, month ] = string.split('-');
		return new Month(parseInt(month), parseInt(year))
	}

	static literal(strings) {
		return Month.from_string(strings[0]);
	}

	static get current() {
		return Month.from_date(new Date());
	}
}

export const literal = Month.literal;