-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathuseCarBehind.tsx
More file actions
83 lines (71 loc) · 2.72 KB
/
Copy pathuseCarBehind.tsx
File metadata and controls
83 lines (71 loc) · 2.72 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { useMemo } from 'react';
import { useDriverRelatives } from '../../Standings/hooks/useDriverRelatives';
import { useDriverStandings } from '../../Standings/hooks/useDriverPositions';
import { useFasterCarsSettings } from './useFasterCarsSettings';
export const useCarBehind = ({
distanceThreshold,
}: {
distanceThreshold?: number;
}) => {
const settings = useFasterCarsSettings();
const driversStandings = useDriverStandings();
// Use total driver count as buffer to get all cars behind
const allDrivers = useDriverRelatives({ buffer: driversStandings.length });
// Find the player car (delta should be 0 for player)
const myCar = allDrivers.find((driver) => driver.delta === 0);
// Filter out drivers who are in the pits
const drivers = allDrivers.filter((driver) => !driver.onPitRoad);
// Cars behind have a negative delta, so the threshold must be negative.
// Normalize here so the stored value's sign doesn't matter — the settings
// slider saves a positive magnitude, while the default is negative.
const threshold = -Math.abs(distanceThreshold ?? -3);
const fasterCarsFromBehind = useMemo(() => {
if (!myCar || myCar.onPitRoad) {
return [];
}
// Get all cars behind the player (negative delta means behind: other - player < 0)
const carsBehind = drivers.filter(
(driver): driver is typeof driver & { delta: number } =>
typeof driver.delta === 'number' &&
Number.isFinite(driver.delta) &&
driver.delta < 0
);
const filtered = carsBehind.filter((car) => {
// Check distance threshold
if (car.delta < threshold) return false;
// If onlyShowFasterClasses is enabled, only show cars from faster classes
if (settings.onlyShowFasterClasses) {
return (
(car.carClass?.relativeSpeed ?? 0) >
(myCar?.carClass?.relativeSpeed ?? 0)
);
}
// Otherwise show all cars (including same class)
return true;
});
return filtered
.sort((a, b) => b.delta - a.delta) // Sort by closest first (least negative delta)
.slice(0, settings.numberDriversBehind) // Take only the configured number
.map((car) => {
const percent = parseInt(
(100 - (Math.abs(car.delta ?? 0) / 3) * 100).toFixed(0)
);
return {
carIdx: car.carIdx,
name: car.driver?.name,
license: car.driver?.license,
rating: car.driver?.rating,
distance: parseFloat(car.delta?.toFixed(1) ?? '0'),
classColor: car.carClass?.color,
percent: percent,
};
});
}, [
drivers,
myCar,
threshold,
settings.numberDriversBehind,
settings.onlyShowFasterClasses,
]);
return fasterCarsFromBehind;
};