Skip to content

Instantly share code, notes, and snippets.

@Fraasi
Last active February 13, 2025 07:49
Show Gist options
  • Save Fraasi/fd5e6c5a3bfe7d0c847967cbccb856dd to your computer and use it in GitHub Desktop.
Save Fraasi/fd5e6c5a3bfe7d0c847967cbccb856dd to your computer and use it in GitHub Desktop.
parsii nässyn jäät dataa
// ==========================================
// earlier own solution before using d3 to count, same results though ­ƒÿü­ƒñù
function stats(data: FinalJson) {
const frozeArr: Date[] = []
const meltArr: Date[] = []
const durationArr: number[] = []
for (const d of data) {
// const frozeDate = parseDate(d.Jäätyminen)
const [fday, fmonth, fyear] = d.Jäätyminen.split('.')
const [mDay, mMonth, mYear] = d.J├ñ├ñnl├ñht├Â.split('.')
frozeArr.push(new Date(`${fyear}-${fmonth}-${fday}`))
meltArr.push(new Date(`${mYear}-${mMonth}-${mDay}`))
durationArr.push(Number(d.Jääpeitekauden_kesto))
}
function sortByMonthAndDate(dates) {
// Compare months using the custom order
const months = [8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7]
const sortedDates = [...dates].sort((a, b) => {
const monthA = a.getMonth() + 1; // getMonth() returns 0-11, so add 1
const monthB = b.getMonth() + 1;
const dateA = a.getDate();
const dateB = b.getDate();
const monthIndexA = months.indexOf(monthA);
const monthIndexB = months.indexOf(monthB);
if (monthIndexA !== monthIndexB) {
return monthIndexA - monthIndexB;
}
// If months are the same, compare by date
return dateA - dateB;
});
return [sortedDates.at(0), sortedDates.at(-1)]
}
function calculateAverageOfDates(dates: Date[]): Date {
// @ts-ignore
const totalMilliseconds: number = dates.reduce((sum, date) => sum + date.getTime(), 0);
const averageMilliseconds = totalMilliseconds / dates.length;
return new Date(averageMilliseconds);
}
const averages = {
froze: calculateAverageOfDates(frozeArr),
melt: calculateAverageOfDates(meltArr),
duration: Math.round(durationArr.reduce((a, b) => a + b, 0) / durationArr.length),
}
// get indices for finalJson
const froze = sortByMonthAndDate(frozeArr)
const frozIdx1 = frozeArr.indexOf(froze[0])
const frozIdx2 = frozeArr.indexOf(froze[1])
const melt = sortByMonthAndDate(meltArr)
const meltIdx1 = meltArr.indexOf(melt[0])
const meltIdx2 = meltArr.indexOf(melt[1])
const longestDuration: number = Math.max(...durationArr)
const shortestDuration: number = Math.min(...durationArr)
const longestDurationIndex: number = durationArr.indexOf(longestDuration)
const shortestDurationIndex: number = durationArr.indexOf(shortestDuration)
return {
shortestIceDuration: data[shortestDurationIndex],
longestIceDuration: data[longestDurationIndex],
earliestFroze: finalJson[frozIdx1],
latestFroze: finalJson[frozIdx2],
earliestMelt: finalJson[meltIdx1],
latestMelt: finalJson[meltIdx2],
averages
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment