aboutsummaryrefslogtreecommitdiff
path: root/src/view/sort.ts
blob: 3fed7fd024cb9cbe80cc4454ab8df9c99ce7208e (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
import * as Food from 'food'
import * as Search from 'lib/search'

export interface Sort {
  field: Field,
  order: Order,
}

export enum Field {
  Name,
  GlycemicIndex,
  Carbohydrates,
  GlycemicLoad,
}

export enum Order {
  Down,
  Up,
}

export const init: Sort = {
  field: Field.Name,
  order: Order.Down,
}

export function aliments(a1: Food.Aliment, a2: Food.Aliment, sort: Sort) {
  return getField(a1, sort.field) > getField(a2, sort.field)
    ? (sort.order === Order.Down ? 1 : -1)
    : (sort.order === Order.Down ? -1 : 1)
}

function getField(a: Food.Aliment, sort: Field) {
  if (sort === Field.Name) {
    return Search.format(a.name)
  } else if (sort === Field.GlycemicIndex) {
    return a.glycemicIndex
  } else if (sort === Field.Carbohydrates) {
    return a.carbohydrates
  } else {
    return Food.glycemicLoad(a)
  }
}

export function toggle(sort: Sort, field: Field): Sort {
  return {
    field,
    order: sort.field === field ? reverseOrder(sort.order) : Order.Down
  }
}

function reverseOrder(order: Order): Order {
  return order === Order.Down ? Order.Up : Order.Down
}