eletrotupi / tcc/ frontend/lib/utils/history.ts80d91bc2ac14c41ba7e7ed6b4640d9d958a3b41f
1.2 KB | 43 lines Raw
1
// TODO: add a barrel import here ffs
2
import type { HistoryCard, HistoryCategory } from '@/lib/history/types'
3

4
export function mergeAndSort(cards: HistoryCard[][]): HistoryCard[] {
5
  return cards
6
  .flat()
7
  .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
8
}
9

10
export function groupByDate(cards: HistoryCard[]): Record<string, HistoryCard[]> {
11
  return cards.reduce<Record<string, HistoryCard[]>>((acc, card) => {
12
    // If the key for this card is sleep, we have to set the hours to
13
    // mid day since sleep records dont have a specific time
14
    if (card.category === 'sleep') {
15
      const date = new Date(card.timestamp)
16
      date.setHours(12)
17
      card.timestamp = date.toISOString()
18
    }
19

20
    const key = new Date(card.timestamp).toLocaleDateString('pt-BR', {
21
      weekday: 'long',
22
      day: 'numeric',
23
      month: 'long',
24
    });
25

26
    if (card.category === 'sleep') {
27
      console.log("Key for this sleep card", key, card.timestamp)
28
    }
29

30
    // XXX: Hacky as fuck
31
    (acc[key] ??= []).push(card)
32

33
    return acc
34
  }, {})
35
}
36

37
export function filterByCategory(
38
  cards: HistoryCard[],
39
  active: HistoryCategory | 'all',
40
): HistoryCard[] {
41
  if (active === 'all') return cards
42
    return cards.filter(c => c.category === active)
43
}