From d48cafebb277e4ad4b31e883cbe4f55eef9ea4a4 Mon Sep 17 00:00:00 2001 From: Joris Date: Sat, 29 May 2021 19:24:41 +0200 Subject: Rewrite in TypeScript --- src/view/sort.ts | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/view/sort.ts (limited to 'src/view/sort.ts') 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 +} -- cgit v1.2.3