import { ErrorString , InvalidOperationException } from "../../shared" ; import { IParallelEnumerable , TypedData } from "../../types" ; import { nextIteration } from "./_nextIteration" ; import { typeDataToArray } from "./_typeDataToArray" ; type AverageFunc = { param source throws ( source ) : Promise < number > ; param source param selector throws < TSource > ( source , selector ) : Promise < number > ; } ; export const average = async < TSource > ( source , selector ? ) : Promise < number > => { let data ; if ( selector ) { data = nextIteration ( source as IParallelEnumerable < TSource > , selector ) ; } else { data = source . dataFunc as TypedData < number > ; } const values = await typeDataToArray ( data ) ; if ( values . length === 0 ) { throw new InvalidOperationException ( ErrorString . NoElements ) ; } let sum = 0 ; for ( const item of values ) { sum += item ; } return sum / values . length ; } ;