summaryrefslogtreecommitdiff
path: root/tst/duration.spec.ts
blob: bcd50f55603239fceb10c4b53924e3cb40189a90 (plain)
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
import { pipe } from "fp-ts/function";
import * as E from "fp-ts/Either";
import { describe, test, expect } from "bun:test";
import * as D from "../src/duration";

describe("Duration Utility", () => {
  test("get unit should convert correctly", () => {
    expect(D.getMs(1000)).toBe(1000);
    expect(D.getSeconds(1000)).toBe(1);
    expect(D.getMinutes(60000)).toBe(1);
    expect(D.getHours(3600000)).toBe(1);
  });

  test("format should format duration correctly", () => {
    expect(D.format(3600000 + 237 + 5 * 60 * 1000)).toBe("01:05:00.237");
  });
});

describe("DurationBuilder", () => {
  test("createDurationBuilder should create a builder with zero values", () => {
    const builder = D.createDurationBuilder();
    expect(builder.millis).toBe(0);
    expect(builder.seconds).toBe(0);
    expect(builder.minutes).toBe(0);
    expect(builder.hours).toBe(0);
  });

  test("withMillis should set fields correctly and with precedence", () => {
    const builder = pipe(
      D.createDurationBuilder(),
      D.withMillis(0),
      D.withSeconds(20),
      D.withMinutes(30),
      D.withHours(40),
      D.withMillis(10),
    );
    expect(builder.millis).toBe(10);
    expect(builder.seconds).toBe(20);
    expect(builder.minutes).toBe(30);
    expect(builder.hours).toBe(40);
  });

  test("build should calculate total duration correctly", () => {
    const duration = pipe(
      D.createDurationBuilder(),
      D.withMillis(10),
      D.withSeconds(20),
      D.withMinutes(30),
      D.withHours(40),
      D.build,
    );
    expect(duration).toBe(
      10 + 20 * 1000 + 30 * 60 * 1000 + 40 * 60 * 60 * 1000,
    );
  });
});

describe("parse", () => {
  test("should return right for a valid duration", () => {
    expect(D.parse("10 seconds 1 hr 30 min")).toEqual(
      E.right(1 * 60 * 60 * 1000 + 30 * 60 * 1000 + 10 * 1000),
    );
  });

  test("should operate with order", () => {
    expect(D.parse("1 hr 30 min 2 hours")).toEqual(
      E.right(2 * 60 * 60 * 1000 + 30 * 60 * 1000),
    );
  });

  test("returns left for unknown duration unit", () => {
    expect(D.parse("1 xyz")).toEqual(E.left("unknown duration type: xyz"));
  });

  test("return left for invalid number", () => {
    expect(D.parse("abc ms")).toEqual(E.left('bad value: "abc"'));
  });
});