sumE<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 sumE
will be int
. If all values are double
, the return value of sumE will
be double
. If all values are num
or there is a combination of int
and double
, the return value of sumE 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 sumE<TResult extends num>([Selector<T, TResult> selector]) {
IncompatibleTypeError.checkValidTypeOrParam(
T, SumReducers.director.keys, selector);
if (selector == null) {
return SumReducers.director[T](this);
}
num sum;
if (TResult == int) {
sum = 0;
} else {
sum = 0.0;
}
final _iterator = this.iterator;
if (!_iterator.moveNext()) {
throw EnumerableError.isEmpty();
}
do {
sum += selector(_iterator.current);
} while (_iterator.moveNext());
return sum;
}