forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonth-iterator.ts
More file actions
55 lines (49 loc) · 1.42 KB
/
month-iterator.ts
File metadata and controls
55 lines (49 loc) · 1.42 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
/**
* Copyright (c) 2022-present Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
/**
* Iterate from the {@param start} to the {@param end}
*/
export default class MonthIterator {
cursor: [number, number]
end: [number, number]
constructor(start: Date, end: Date) {
if (!start || !end) {
throw new Error("Invalid param")
}
this.cursor = [start.getFullYear(), start.getMonth()]
this.end = [end.getFullYear(), end.getMonth()]
}
hasNext(): boolean {
if (this.cursor[0] === this.end[0]) {
return this.cursor[1] <= this.end[1]
} else {
return this.cursor[0] < this.end[0]
}
}
next(): string {
if (this.hasNext()) {
const [year, month] = this.cursor
const result = year.toString().padStart(4, '0') + (month + 1).toString().padStart(2, '0')
const nextMonth = month + 1
this.cursor[0] += nextMonth >= 12 ? 1 : 0
this.cursor[1] = nextMonth % 12
return result
} else {
return undefined
}
}
forEach(callback: (yearMonth: string) => void) {
while (this.hasNext()) {
callback(this.next())
}
}
toArray(): string[] {
const result = []
this.forEach(yearMonth => result.push(yearMonth))
return result
}
}