eletrotupi / tcc/ api/src/utils/calc.tsc941890054e469bdf624c967e653c5c48b4fb80f
1.2 KB | 50 lines Raw
1
// TODO: Move other calculations here
2
export const avg = (values: number[]) =>
3
  values.reduce((a, b) => a + b, 0) / values.length;
4

5
export const formatHours = (hours: number): string => {
6
  let h = Math.floor(hours);
7
  let m = Math.round((hours - h) * 60);
8

9
  // Rounding to the nearest minute can land on 60; carry it into the hour
10
  if (m === 60) {
11
    h += 1;
12
    m = 0;
13
  }
14

15
  if (m === 0) return `${h}h`;
16

17
  return `${h}h ${m}min`;
18
}
19

20
export const formatDiff = (minutes: number): string => {
21
  const abs = Math.abs(minutes);
22
  const h = Math.floor(abs / 60);
23
  const m = abs % 60;
24
  const sign = minutes > 0 ? "+" : "-";
25

26
  if (h === 0) return `${sign}${m}min`;
27
  if (m === 0) return `${sign}${h}h`;
28

29
  return `${sign}${h}h ${m}min`;
30
}
31

32
export const paginate = (
33
  page: number,
34
  limit: number,
35
  total: number,
36
): { page: number; skip: number; nextPage: number | null } => {
37
  const skip = (page - 1) * limit;
38
  const totalPages = Math.ceil(total / limit);
39

40
  return {
41
    page,
42
    skip,
43
    nextPage: page < totalPages ? page + 1 : null,
44
  };
45
}
46

47
export const timeToCron = (time: string): string => {
48
  const [hour, minute] = time.split(":").map(Number);
49
  return `${minute} ${hour} * * *`;
50
}