I am developing a drink tracker which would also be able to predict how long it takes approximately until the user fully sobers up after drinking.
I implemented the following logic for the BAC calculation:
const calculateCurrentBAC = (drinkHistory: DrinkHistoryItem[]) => {
const currentDate = new Date();
let currentBAC = 0;
drinkHistory.forEach((historyItem) => {
const pastDate = new Date(historyItem.date);
const differenceInMilliseconds = currentDate.getTime() - pastDate.getTime();
const differenceInMinutes = differenceInMilliseconds / 1000 / 60;
const initialBAC = historyItem.bac;
const bacEliminated =
initialBAC -
(differenceInMinutes / 60) * ALCOHOL_ELIMINATION_RATE_PER_HOUR;
const bacAfterElimination = Math.max(bacEliminated, 0);
const minutesUntilSober =
(currentBAC / ALCOHOL_ELIMINATION_RATE_PER_HOUR) * 60;
console.log(minutesUntilSober);
currentBAC += bacAfterElimination;
});
When I am adding a drink in the app, the BAC level after the given drink is saved as a property to the object which gets added to the DrinkHistory array. (Meaning it always assumes the user had a BAC level of 0 and adds the BAC level after the user consumed the drink).
This BAC level is taken as a base and then for each drink I calculate the current BAC level with an alcohol elimination constant of 0.015 BAC / hour.
These BAC levels are then added up and their sum is the current BAC level of the user.
From this BAC level I then derive the time it takes for the user to completely sober up. I do this with the same constant I use for calculating the current BAC level for each separate drink.
The problem arises when I test (currently just a console log) the decay in real time. There is a huge discrepancy between the assumed decay and the real life decay.
For example if I input 3x500ml beer at 10:00, then at first it says it takes 456 minutes to sober up which is correct because I checked with multiple online calculators as well as apps.
But if I fast forward to 12:00, (2 hours passed!) this calculation says there are 96 minutes left until sobriety which cannot be true since it would mean 6 hours passed already.
Where is my logic going wrong?