Skip to content

Commit

Permalink
Sort batteries with active_battery_service first, then charging > dis…
Browse files Browse the repository at this point in the history
…charging > idle, then id
  • Loading branch information
mman committed Jul 22, 2024
1 parent 833c573 commit 37768e8
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions src/app/Marine2/utils/helpers/devices/batteries/sort-batteries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,29 @@ import { BATTERY } from "../../../constants/devices/batteries"
import { Battery as BatteryType } from "@victronenergy/mfd-modules"

/*
Sort batteries by state (charging > discharging > idle) and within that by id.
Push batteries with active_battery_service to the front.
Then sort by state (charging(1) > discharging(2) > idle(0)), lastly by id (alphanumerically).
*/
export const sortBatteries = (batteries: BatteryType[]) =>
batteries.slice().sort((a, b) => {
if (
(a.state === BATTERY.CHARGING && b.state !== BATTERY.CHARGING) ||
(a.state === BATTERY.DISCHARGING && b.state === BATTERY.IDLE) ||
((a.state || a.state === 0) && !b.state && b.state !== 0)
)
return -1

if (
(a.state !== BATTERY.CHARGING && b.state === BATTERY.CHARGING) ||
(a.state === BATTERY.IDLE && b.state === BATTERY.DISCHARGING) ||
(!a.state && a.state !== 0 && (b.state || b.state === 0))
)
// same active_battery_service
if (a.active_battery_service === b.active_battery_service) {
// same state
if (a.state === b.state) {
// sort by id (alphanumerically)
return a.id.localeCompare(b.id)
}
// different state
if (a.state === BATTERY.CHARGING) {
// a is charging, a goes before b
return -1
} else if (a.state === BATTERY.DISCHARGING && b.state !== BATTERY.CHARGING) {
// a is discharging, b is not charging, a goes before b
return -1
}
// b must go before a
return 1

return +a.id - +b.id
}
// a has active_battery_service, a goes before b
return a.active_battery_service ? -1 : 1
})

0 comments on commit 37768e8

Please sign in to comment.