Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort batteries with active_battery_service first #371

Merged
merged 4 commits into from
Jul 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
})
Loading