I am trying to model the water level of a bucket. The bucket has a max Limit of 1000 m^3. The inflow rate is 50 m^3/s. Randomly, a known but variable amount of water is taken out of bucket.
I have to keep track of the current volume of water present in the bucket.
I have written the following program to solve the problem.
/**
* An extended version of redux store, that constantly restores a numeric value
* unitll the provided max value is reached.
*/
export function createStore(reducer, options) {
const {
maxLevel = 1000,
restoreRate = 50, // per second
restoreAction = "increment",
} = options || {};
let state = maxLevel;
let isRestoring = false;
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
if (state < 1000 && !isRestoring) {
restore();
}
};
const restore = async () => {
isRestoring = true;
await wait(1000);
isRestoring = false;
dispatch({
type: restoreAction,
payload: Math.min(restoreRate, maxLevel - state),
});
};
const wait = async (milliseconds) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, milliseconds);
});
};
return {
getState,
dispatch,
};
}
export function reducer(state, action) {
switch (action.type) {
case "increment":
return state + action.payload;
case "decrement":
return state - action.payload;
default:
return state;
}
}
Looking for suggestions to improve the above mentioned solution and also alternate approaches to model this behaviour.