For the first advent of code challenge this year, I decided to experiment with reducers. The following code worked perfectly:
export default class CalorieCounter {
public static calculateMaxInventoryValue(elfInventories: number[][]): number {
const sumInventoriesReducer = (
acc: number[],
element: number[]
): number[] => [...acc, this.sumCalories(element)];
return Math.max(...elfInventories.reduce(sumInventoriesReducer, []));
}
private static sumCalories(inventory: number[]): number {
return inventory.reduce((a: number, b: number) => a + b, 0);
}
}
Later on, I attempted to separate the sumInventoriesReducer into its own private function within the same class. Unfortunately, this new code did not work as expected:
export default class CalorieCounter {
public static calculateMaxInventoryValue(elfInventories: number[][]): number {
return Math.max(...elfInventories.reduce(this.sumInventoriesReducer, []));
}
private static sumInventoriesReducer(
acc: number[],
element: number[]
): number[] {
return [...acc, this.sumCalories(element)];
}
private static sumCalories(inventory: number[]): number {
return inventory.reduce((a: number, b: number) => a + b, 0);
}
}
The logic remains the same in both versions, the only change being the extraction of the reducer into a private function (the static keyword is not the issue, as I tried without it and encountered the same error).
The specific error message that appeared is:
TypeError: Cannot read property 'sumCalories' of undefined
20 | element: number[]
21 | ): number[] {
> 22 | return [...acc, this.sumCalories(element)];
| ^
23 | }
24 |
25 | private static sumCalories(inventory: number[]): number {
I am striving to approach this problem from an object-oriented perspective, even though I understand that reducers are typically associated with functional programming. Is there anyone who can offer guidance on how to make this private class function work properly?