Skip to content

Commit 37768e8

Browse files
committed
Sort batteries with active_battery_service first, then charging > discharging > idle, then id
1 parent 833c573 commit 37768e8

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

src/app/Marine2/utils/helpers/devices/batteries/sort-batteries.ts

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,29 @@ import { BATTERY } from "../../../constants/devices/batteries"
22
import { Battery as BatteryType } from "@victronenergy/mfd-modules"
33

44
/*
5-
Sort batteries by state (charging > discharging > idle) and within that by id.
5+
Push batteries with active_battery_service to the front.
6+
Then sort by state (charging(1) > discharging(2) > idle(0)), lastly by id (alphanumerically).
67
*/
78
export const sortBatteries = (batteries: BatteryType[]) =>
89
batteries.slice().sort((a, b) => {
9-
if (
10-
(a.state === BATTERY.CHARGING && b.state !== BATTERY.CHARGING) ||
11-
(a.state === BATTERY.DISCHARGING && b.state === BATTERY.IDLE) ||
12-
((a.state || a.state === 0) && !b.state && b.state !== 0)
13-
)
14-
return -1
15-
16-
if (
17-
(a.state !== BATTERY.CHARGING && b.state === BATTERY.CHARGING) ||
18-
(a.state === BATTERY.IDLE && b.state === BATTERY.DISCHARGING) ||
19-
(!a.state && a.state !== 0 && (b.state || b.state === 0))
20-
)
10+
// same active_battery_service
11+
if (a.active_battery_service === b.active_battery_service) {
12+
// same state
13+
if (a.state === b.state) {
14+
// sort by id (alphanumerically)
15+
return a.id.localeCompare(b.id)
16+
}
17+
// different state
18+
if (a.state === BATTERY.CHARGING) {
19+
// a is charging, a goes before b
20+
return -1
21+
} else if (a.state === BATTERY.DISCHARGING && b.state !== BATTERY.CHARGING) {
22+
// a is discharging, b is not charging, a goes before b
23+
return -1
24+
}
25+
// b must go before a
2126
return 1
22-
23-
return +a.id - +b.id
27+
}
28+
// a has active_battery_service, a goes before b
29+
return a.active_battery_service ? -1 : 1
2430
})

0 commit comments

Comments
 (0)