aboutsummaryrefslogtreecommitdiff
path: root/src/duration.ts
blob: 5c2cceacdeeda7c4ba17a763ae014db73c08b98c (plain) (blame)
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
import moment from 'moment';

export type TimeUnit = moment.unitOfTime.DurationConstructor;

export type DurationFlat = {
    value: string,
    unit: string
};

export class Duration {
    value: string;
    unit: TimeUnit;
    constructor(value: string, unit: TimeUnit) {
        this.value = value
        this.unit = unit
    }

    isValid() { return moment.duration(parseInt(this.value), this.unit).isValid(); }
    toMoment() {
        let m = moment.duration(parseInt(this.value), this.unit);
        if (m.isValid()) return m;
        return null;
    }

    static days(n: number) { return new Duration(String(n), 'days'); }
    static weeks(n: number) { return new Duration(String(n), 'weeks'); }
    static months(n: number) { return new Duration(String(n), 'months'); }

    deflate() { return { value: this.value, unit: this.unit }; }
    static inflate = (obj: DurationFlat) => new Duration(obj.value, obj.unit as TimeUnit);
}


export type TrackedPeriodFlat = {
    name: string,
    start: DurationFlat,
    end: DurationFlat
};

export class TrackedPeriod {
    name: string;
    start: Duration;
    end: Duration;

    constructor(name: string, start: Duration, end: Duration) {
        this.name = name;
        this.start = start;
        this.end = end;
    }

    deflate() {
        return {
            name: this.name,
            start: this.start.deflate(),
            end: this.end.deflate()
        };
    }

    static inflate = (obj: TrackedPeriodFlat) => (
        new TrackedPeriod(obj.name,
            Duration.inflate(obj.start),
            Duration.inflate(obj.end))
    );
}