Sum<TResult extends num> method
Calculates the sum of the elements in an enumerable, optionally using
selector
to obtain the value to be summed.
Iterates over the entire enumerable, passing each element to the
selector
function and adding its return value to a running total. Once
iteration is complete, the total is returned.
The type of the returned total is dependent on the value returned by the
selector
function. If all values are int
, the return value of Sum
will be int
. If all values are double
, the return value of Sum will
be double
. If all values are num
or there is a combination of int
and double
, the return value of Sum will be num
.
When the type of the enumerable is a numeric primitive (e.g. int
,
double
, or num
), the selector
function can be omitted. If so,
the elements themselves are added to the running total.
If the type of the enumerable is not a numeric primitive, the selector
function must be provided. Otherwise, an ArgumentError
is thrown.
Implementation
TResult Sum<TResult extends num>([Selector<T, TResult> selector]) {
if (selector == null && T != num && T != int && T != double)
throw ArgumentError(
'`selector` must not be null or the type of this enumerable must be one of the following: ${[
num,
int,
double
]}');
if (selector == null) {
if (T == num) return EnumerableReducers.SumNum(this as Enumerable<num>);
if (T == int)
return EnumerableReducers.SumInt(this as Enumerable<int>) as TResult;
if (T == double)
return EnumerableReducers.SumDouble(this as Enumerable<double>)
as TResult;
throw UnexpectedStateError();
}
num sum;
if (TResult == int)
sum = 0;
else
sum = 0.0;
final _iterator = this.iterator;
if (!_iterator.moveNext()) {
throw EmptyEnumerableError();
}
do {
sum += selector(_iterator.current);
} while (_iterator.moveNext());
return sum;
}