impl/typescript.ts
1,098 bytes · the TypeScript implementation · view raw
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { roundDiv } from "./math_round_div.ts"; ← from math.round-div ^1.0.0 · built alongside by fune
import { type PvArray, type SolarEstimate } from "./energy_solar_generation_types.ts";
// watts x Kk x SF (hundredths) / (1000 W/kW x 100) is kWh.
const DIVISOR = 100_000;
function check(what: string, value: number, max: number): void {
if (!Number.isInteger(value) || value < 0 || value > max) {
throw new RangeError(`${what} must be a whole number from 0 to ${max}, received ${value}`);
}
}
/**
* Annual AC generation by the MCS method, kWp x Kk x SF, rounded half-up to a
* whole kWh for each array; the total is the sum of the arrays.
*/
export function solarGeneration(arrays: readonly PvArray[]): SolarEstimate {
if (arrays.length === 0) {
throw new RangeError("a solar estimate needs at least one array");
}
const kwh = arrays.map((a) => {
check("wattsPeak", a.wattsPeak, 100_000_000);
check("kk", a.kk, 5000);
check("shadeFactor", a.shadeFactor, 100);
return roundDiv(a.wattsPeak * a.kk * a.shadeFactor, DIVISOR, "half-up");
});
return { arrays: kwh, total: kwh.reduce((sum, k) => sum + k, 0) };
}