Mein Sohn hat es gelöst:
let start = 21 // values 0-23
let timePeriod = 4 // values 1-5
const allPrices = {
0: 0.1,
1: 0.26,
2: 0.32,
3: 0.38,
4: 0.31,
5: 0.122,
6: 0.25,
7: 0.35,
8: 0.177,
9: 0.366,
10: 0.14,
11: 0.288,
12: 0.1,
13: 0.344,
14: 0.1,
15: 0.322,
16: 0.1,
17: 0.377,
18: 0.1,
19: 0.266,
20: 0.1,
21: 0.37,
22: 0.13,
23: 0.25,
}
const averagePrice = startCalc(start, timePeriod)
console.log(averagePrice)
function startCalc(start, timePeriod) {
const prices = Object.values(allPrices)
const earlyTimePeriod = -24 + (start + timePeriod)
const lateTimePeriod = 24 - (start)
let hourPrices
if(earlyTimePeriod <= 0) { // for hours 0-19
hourPrices = calcPrices(prices, 'default', timePeriod, start)
} else { // for hours 20-23
let earlyHourPrices = calcPrices(prices, 'early', earlyTimePeriod)
let lateHourPrices = calcPrices(prices, 'late', lateTimePeriod)
hourPrices = earlyHourPrices + lateHourPrices
}
return calcAveragePrice(hourPrices, timePeriod)
}
function calcPrices(pricesArr, checkHours, timePeriod, start) {
const prices = checkHours === 'late' ? pricesArr.reverse() : pricesArr
const key = start || 0
let sum
if(timePeriod === 1) {
sum = prices[key]
} else if (timePeriod === 2) {
sum = prices[key] + prices[key + 1]
} else if (timePeriod === 3) {
sum = prices[key] + prices[key + 1] + prices[key + 2]
} else if (timePeriod === 4) {
sum = prices[key] + prices[key + 1] + prices[key + 2] + prices[key + 3]
} else if (timePeriod === 5) {
sum = prices[key] + prices[key + 1] + prices[key + 2] + prices[key + 3] + prices[key + 4]
}
return sum
}
function calcAveragePrice(hourPrices, timePeriod) {
const averagePrice = hourPrices / timePeriod
return averagePrice
}
natürlich sollte man oben die Tibber Preise aus den Objekten auslesen und dort einfügen. Die Zahlen sind reine Fantasiezahlen zum Testen