I am trying to find the largest item in an array.
It was simple enough to solve using the straight-forward, simple, clean, elegant, fast method – iterating the array:
private GetMaxValue(data: Array<RealtimeDataPoint>): number { if (data.length === 0) return 0; var maxValue = data[0].Value; for (var i: number = 1; i < data.length; i++) { if (data[i].Value > maxValue) maxValue = data[i].Value; } return maxValue; }
But that’s not cool
Then, rather than solving the problem using the easy way, i wanted to try to solve it using .reduce
:
private GetMaxValue(data: Array<RealtimeDataPoint>): number { var pt: RealtimeDataPoint = data.reduce(function (previousValue: RealtimeDataPoint, currentValue: RealtimeDataPoint, currentIndex: number, array: Array<RealtimeDataPoint>): RealtimeDataPoint { if (currentValue.Value > previousValue.Value) return currentValue; else return previousValue; }); if (pt != null) return pt.Value; else return 0; }
And it’s great, and it compiles and all. But it crashes at runtime:
Object doesn’t support this action
It seems to indicate that something on the var pt: RealtimeDataPoint = data.reduce(...)
line doesn’t work, since that’s the line it stalls on:
And it’s not the .reduce
member that it doesn’t support, because that’s there.
So, two questions:
- what is wrong with my syntax?
- why didn’t TypeScript realize there was something wrong with my syntax?
Bonus Chatter
- Internet Explorer 11
- Chrome 32
Advertisement
Answer
Solved it.
The error message from Internet Explorer 11 is:
Object doesn’t support this action
The error message from Chrome 32 is:
Reduce of empty array with no initial value
With that the fix is simple; borrow something from the elegant solution:
private GetMaxValue(data: Array<RealtimeDataPoint>): number { if (data.length === 0) return 0; var pt: RealtimeDataPoint = data.reduce(function (previousValue: RealtimeDataPoint, currentValue: RealtimeDataPoint, currentIndex: number, array: Array<RealtimeDataPoint>): RealtimeDataPoint { if (currentValue.Value > previousValue.Value) return currentValue; else return previousValue; }); if (pt != null) return pt.Value; else return 0; }
Given the verbosity of the reduce
pattern, and the associated performance penalty, i think i’ll stick with the elegant solution.
But at least now there’s an example of the reduce
syntax in TypeScript.
Note: Any code released into public domain. No attribution required.