refactor: centralize lake metrics calculations into a utility module with comprehensive unit tests
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
export interface LakeCalculationConfig {
|
||||
maxVolume?: number;
|
||||
minLevel?: number;
|
||||
maxLevel?: number;
|
||||
storageLevel?: number;
|
||||
}
|
||||
|
||||
export interface LakeMetrics {
|
||||
capacity: number; // 0-100 percentage
|
||||
volume: number; // in mil. m3
|
||||
storageDiff: number; // in meters
|
||||
}
|
||||
|
||||
export function calculateLakeMetrics(
|
||||
currentLevel: number,
|
||||
reportedVolume: number,
|
||||
config: LakeCalculationConfig
|
||||
): LakeMetrics {
|
||||
let capacity = 0;
|
||||
let volume = reportedVolume;
|
||||
let storageDiff = 0;
|
||||
|
||||
// 1. Calculate capacity and volume
|
||||
if (volume > 0 && config.maxVolume && config.maxVolume > 0) {
|
||||
// If real volume is available, calculate capacity from volume
|
||||
capacity = Math.max(0, Math.min(100, Math.round((volume / config.maxVolume) * 1000) / 10));
|
||||
} else if (config.minLevel && config.maxLevel && currentLevel > 0) {
|
||||
// Fallback: estimate capacity and volume from level difference
|
||||
const percentage = ((currentLevel - config.minLevel) / (config.maxLevel - config.minLevel)) * 100;
|
||||
capacity = Math.max(0, Math.min(100, Math.round(percentage * 10) / 10)); // Round to 1 decimal place
|
||||
|
||||
if (volume === 0) {
|
||||
volume = Number(((capacity / 100) * (config.maxVolume || 0)).toFixed(1));
|
||||
}
|
||||
} else {
|
||||
// Missing required config data or bad level
|
||||
if (volume === 0) {
|
||||
volume = config.maxVolume || 0;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Calculate storage difference
|
||||
if (config.storageLevel && currentLevel > 0) {
|
||||
storageDiff = Number((currentLevel - config.storageLevel).toFixed(2));
|
||||
}
|
||||
|
||||
return {
|
||||
capacity,
|
||||
volume,
|
||||
storageDiff
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user