diff options
author | Joris | 2021-05-29 19:24:41 +0200 |
---|---|---|
committer | Joris | 2021-05-29 19:24:41 +0200 |
commit | d48cafebb277e4ad4b31e883cbe4f55eef9ea4a4 (patch) | |
tree | 7f04fb49defa5fbc7984b0eee60bb7ce16a37ae2 /src/view/sort.ts | |
parent | 4e3cd92a8063a70dab9ae0ccafd0552c78c6e005 (diff) |
Rewrite in TypeScript
Diffstat (limited to 'src/view/sort.ts')
-rw-r--r-- | src/view/sort.ts | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/src/view/sort.ts b/src/view/sort.ts new file mode 100644 index 0000000..3fed7fd --- /dev/null +++ b/src/view/sort.ts @@ -0,0 +1,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 +} |