This repository has been archived by the owner on Dec 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
TimeQuantity.ts
105 lines (92 loc) · 2.54 KB
/
TimeQuantity.ts
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
96
97
98
99
100
101
102
103
104
105
/*!
* @author electricessence / https://github.com/electricessence/
* Licensing: MIT https://github.com/electricessence/TypeScript.NET/blob/master/LICENSE.md
*/
import {areEqual, compare} from "../Compare";
import {TimeUnit} from "./TimeUnit";
import {Milliseconds, Ticks} from "./HowMany";
import {IEquatable} from "../IEquatable";
import {IComparable} from "../IComparable";
import {ITimeQuantity} from "./ITimeQuantity";
import {ITimeMeasurement} from "./ITimeMeasurement";
import {Lazy} from "../Lazy";
/**
* This class provides a simple means for storing and calculating time quantities.
*/
export class TimeQuantity implements IEquatable<ITimeQuantity>, IComparable<ITimeQuantity>, ITimeQuantity
{
constructor(protected _quantity:number = 0)
{
this._resetTotal();
}
// Provides an overridable mechanism for extending this class.
getTotalMilliseconds():number
{
return this._quantity;
}
/**
* +1, 0, or -1 depending on the time direction.
* @returns {number}
*/
get direction():number
{
return compare(this.getTotalMilliseconds(), 0);
}
/**
* Compares this instance against any other time quantity instance and return true if the amount of time is the same.
* @param other
* @returns {boolean}
*/
equals(other:ITimeQuantity):boolean
{
return areEqual(this.getTotalMilliseconds(), other && other.total && other.total.milliseconds);
}
/**
* Compares this instance against any other time quantity instance.
* @param other
* @returns {number}
*/
compareTo(other:ITimeQuantity):number
{
return compare(this.getTotalMilliseconds(), other && other.total && other.total.milliseconds);
}
// @ts-ignore;
protected _total:Lazy<ITimeMeasurement>;
protected _resetTotal():void
{
const t = this._total;
if(!t || t.isValueCreated)
{
this._total = Lazy.create(() =>
{
const ms = this.getTotalMilliseconds();
return <ITimeMeasurement>Object.freeze({
ticks: ms*Ticks.Per.Millisecond,
milliseconds: ms,
seconds: ms/Milliseconds.Per.Second,
minutes: ms/Milliseconds.Per.Minute,
hours: ms/Milliseconds.Per.Hour,
days: ms/Milliseconds.Per.Day,
});
});
}
}
/**
* Returns an object with all units exposed as totals.
* @returns {ITimeMeasurement}
*/
get total():ITimeMeasurement
{
return this._total.value;
}
/**
* Returns the total amount of time measured in the requested TimeUnit.
* @param units
* @returns {number}
*/
getTotal(units:TimeUnit):number
{
return TimeUnit.fromMilliseconds(this.getTotalMilliseconds(), units);
}
}
export default TimeQuantity;