aboutsummaryrefslogtreecommitdiff
path: root/src/lib/utils/readable_time.ts
blob: 86ba044843514d01a4027d2587c10e01ee8111a3 (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
type DateMagnitude = 'day' | 'hour' | 'minute' | 'second';

type ReadableTime = {
  count: number,
  label: string
};


const internals = {
  magnitudes: {
    day: 86400000,
    hour: 3600000,
    minute: 60000,
    second: 1000
  },
  labels: {
    day: 'time.days',
    hour: 'time.hours',
    minute: 'time.minutes',
    second: 'time.seconds'
  },

  makeTimeReadable(time: number, magnitude: DateMagnitude): ReadableTime {

    return {
      count: Math.floor(time / internals.magnitudes[magnitude]),
      label: internals.labels[magnitude]
    };
  }
};

export const readableTime = function readableTime(time: number): ReadableTime {

  switch (true) {
  case time >= internals.magnitudes.day:
    return internals.makeTimeReadable(time, 'day');
  case time >= internals.magnitudes.hour:
    return internals.makeTimeReadable(time, 'hour');
  case time >= internals.magnitudes.minute:
    return internals.makeTimeReadable(time, 'minute');
  case time < 0:
    return internals.makeTimeReadable(0, 'second');
  default:
    return internals.makeTimeReadable(time, 'second');
  }
};