-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic-date.js
95 lines (83 loc) · 2.09 KB
/
basic-date.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
94
95
/**
* BasicDate
* @classdesc An abstract data type for Dates.
* @implements {Comparable}
* @see p. 79, 91, 103, 247
*/
class BasicDate {
constructor () {
let month, day, year
if (arguments.length === 1 && typeof arguments[0] === 'string') {
const parts = arguments[0].split('/')
month = parseInt(parts[0], 10)
day = parseInt(parts[1], 10)
year = parseInt(parts[2], 10)
} else if (arguments.length === 3) {
month = arguments[0]
day = arguments[1]
year = arguments[2]
}
// immutable properties
Object.defineProperties(this, {
_month: { value: month },
_day: { value: day },
_year: { value: year }
})
}
/**
* Returns the date's month
*/
month () {
return this._month
}
/**
* Returns the date's day
*/
day () {
return this._day
}
/**
* Returns the date's year
*/
year () {
return this._year
}
/**
* Returns the date as string
* @example
* // '9/27/1987'
*/
toString () {
return `${this.month()}/${this.day()}/${this.year()}`
}
/**
* Returns if this date is equal to another date
* @param {BasicDate} target The target BasicDate
* @returns {boolean}
*/
equals (target) {
if (this === target) return true
if (target === null) return false
if (!(target instanceof BasicDate)) return false
if (this.day() !== target.day()) return false
if (this.month() !== target.month()) return false
if (this.year() !== target.year()) return false
return true
}
/**
* Returns if this date is greater (+1),
* smaller (-1) or equal (0) to another date.
* @param {BasicDate} target The target BasicDate
* @returns {number} +1 (greater than), -1 (smaller than), 0 (equal to)
*/
compareTo (target) {
if (this.year() > target.year()) return +1
if (this.year() < target.year()) return -1
if (this.month() > target.month()) return +1
if (this.month() < target.month()) return -1
if (this.day() > target.day()) return +1
if (this.day() < target.day()) return -1
return 0
}
}
module.exports = BasicDate