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