forked from Disciplr-Org/Disciplr-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortPending.ts
More file actions
49 lines (43 loc) · 1.34 KB
/
Copy pathsortPending.ts
File metadata and controls
49 lines (43 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import type { ValidationTask } from '../Zustand/Store';
export type PendingSortKey = 'deadline' | 'amount' | 'vaultName';
export type SortDirection = 'asc' | 'desc';
const parseAmount = (amount: string): number => {
const match = amount.replace(/,/g, '').match(/-?\d+(\.\d+)?/);
return match ? Number(match[0]) : 0;
};
const parseDeadline = (task: ValidationTask): number => {
const timestamp = Date.parse(task.deadline);
return Number.isNaN(timestamp) ? Number.POSITIVE_INFINITY : timestamp;
};
const compareTasks = (
a: ValidationTask,
b: ValidationTask,
key: PendingSortKey,
): number => {
switch (key) {
case 'amount':
return parseAmount(a.amount) - parseAmount(b.amount);
case 'vaultName':
return a.vaultName.localeCompare(b.vaultName, undefined, {
sensitivity: 'base',
numeric: true,
});
case 'deadline':
default:
return parseDeadline(a) - parseDeadline(b);
}
};
export function sortPending(
tasks: ValidationTask[],
key: PendingSortKey,
dir: SortDirection,
): ValidationTask[] {
const direction = dir === 'desc' ? -1 : 1;
return tasks
.map((task, index) => ({ task, index }))
.sort((a, b) => {
const compared = compareTasks(a.task, b.task, key);
return compared === 0 ? a.index - b.index : compared * direction;
})
.map(({ task }) => task);
}