webapp/src/lib/sort.ts

60 lines
1.5 KiB
TypeScript
Raw Normal View History

import type { Author, Maybe, Reaction, Shout, Topic, TopicStat } from '~/graphql/schema/core.gen'
2022-09-13 09:59:04 +00:00
2024-07-12 12:10:22 +00:00
export const byFirstChar = (a: Author | Topic, b: Author | Topic) =>
((a as Author).name || (a as Topic).title || '').localeCompare(
(b as Author).name || (b as Topic).title || ''
)
2022-09-09 11:53:35 +00:00
2022-10-07 19:35:53 +00:00
export const byCreated = (a: Shout | Reaction, b: Shout | Reaction) => {
2023-11-28 13:18:25 +00:00
return a?.created_at - b?.created_at
2022-09-09 11:53:35 +00:00
}
export const byPublished = (a: Shout, b: Shout) => {
2024-02-17 14:40:10 +00:00
return (a?.published_at || 0) - (b?.published_at || 0)
}
2022-10-07 19:35:53 +00:00
export const byLength = (
a: (Shout | Reaction | Topic | Author)[],
2024-06-26 08:22:05 +00:00
b: (Shout | Reaction | Topic | Author)[]
2022-10-07 19:35:53 +00:00
) => {
2022-09-09 11:53:35 +00:00
const x = a.length
const y = b.length
if (x > y) return -1
if (x < y) return 1
return 0
}
2024-06-28 07:47:38 +00:00
export type SomeStat = { [x: string]: Maybe<number> } | undefined | null
2024-06-24 17:50:27 +00:00
export const byStat = (metric: string) => {
2024-07-05 19:40:54 +00:00
if (metric === 'name' || metric === 'title') return byFirstChar
2024-06-28 07:47:38 +00:00
return (a: { stat?: SomeStat }, b: { stat?: SomeStat }) => {
2024-06-24 17:50:27 +00:00
const aStat = a.stat?.[metric] ?? 0
const bStat = b.stat?.[metric] ?? 0
return aStat - bStat
2022-09-09 11:53:35 +00:00
}
}
2022-09-22 09:37:49 +00:00
export const byTopicStatDesc = (metric: keyof TopicStat) => {
return (a: Topic, b: Topic) => {
2024-02-04 09:03:15 +00:00
const x = a.stat?.[metric] || 0
const y = b.stat?.[metric] || 0
2022-09-22 09:37:49 +00:00
if (x > y) return -1
if (x < y) return 1
return 0
}
}
2024-01-25 19:16:38 +00:00
export const byScore = () => {
2024-06-24 17:50:27 +00:00
return (a: { score: number }, b: { score: number }) => {
2024-01-25 19:16:38 +00:00
const x = a?.score || 0
const y = b?.score || 0
if (x > y) return -1
if (x < y) return 1
return 0
}
}