webapp/src/utils/sortby.ts

62 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-12-24 13:08:04 +00:00
import type { Author, Reaction, Shout, Stat, Topic, TopicStat } from '../graphql/schema/core.gen'
2022-09-13 09:59:04 +00:00
2022-09-09 11:53:35 +00:00
export const byFirstChar = (a, b) => (a.name || a.title || '').localeCompare(b.name || b.title || '')
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) => {
return a.published_at - b.published_at
}
2022-10-07 19:35:53 +00:00
export const byLength = (
a: (Shout | Reaction | Topic | Author)[],
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
}
2022-11-23 11:57:14 +00:00
export const byStat = (metric: keyof Stat | keyof TopicStat) => {
2022-09-09 11:53:35 +00:00
return (a, b) => {
const x = (a?.stat && a.stat[metric]) || 0
const y = (b?.stat && b.stat[metric]) || 0
if (x > y) return -1
if (x < y) return 1
return 0
}
}
2022-09-22 09:37:49 +00:00
export const byTopicStatDesc = (metric: keyof TopicStat) => {
return (a: Topic, b: Topic) => {
const x = (a?.stat && a.stat[metric]) || 0
const y = (b?.stat && b.stat[metric]) || 0
if (x > y) return -1
if (x < y) return 1
return 0
}
}
2024-01-25 19:16:38 +00:00
export const byScore = () => {
return (a, b) => {
const x = a?.score || 0
const y = b?.score || 0
if (x > y) return -1
if (x < y) return 1
return 0
}
}
2022-09-09 11:53:35 +00:00
export const sortBy = (data, metric) => {
const x = [...data]
x.sort(typeof metric === 'function' ? metric : byStat(metric))
return x
}