-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathdate-iterator.ts
More file actions
59 lines (52 loc) · 1.35 KB
/
date-iterator.ts
File metadata and controls
59 lines (52 loc) · 1.35 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
/**
* Copyright (c) 2023-present Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import { MILL_PER_DAY, formatTimeYMD, isSameDay } from "./time"
/**
* Iterate from the {@param start} to the {@param end}
*/
export default class DateIterator {
cursor: Date
end: Date
constructor(start: Date, end: Date) {
if (!start || !end) {
throw new Error("Invalid param")
}
this.cursor = start
this.end = end
}
hasNext(): boolean {
if (this.cursor <= this.end) {
return true
}
return isSameDay(this.cursor, this.end)
}
next(): IteratorResult<string> {
if (this.hasNext()) {
const value = formatTimeYMD(this.cursor)
this.cursor = new Date(this.cursor.getTime() + MILL_PER_DAY)
return {
value,
done: false,
}
} else {
return {
value: null,
done: true,
}
}
}
forEach(callback: (yearMonthDate: string) => void) {
while (this.hasNext()) {
callback(this.next().value)
}
}
toArray(): string[] {
const result: string[] = []
this.forEach(yearMonth => result.push(yearMonth))
return result
}
}