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 }