UNPKG

1.6 kBSource Map (JSON)View Raw
1{"version":3,"sources":["iterable/average.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAK5C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,OAAO,CAAC,MAAqB,EAAE,WAA+B,QAAQ;IACpF,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE;QACzB,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;QACtB,KAAK,EAAE,CAAC;KACT;IAED,IAAI,KAAK,KAAK,CAAC,EAAE;QACf,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;KACrC;IAED,OAAO,GAAG,GAAG,KAAK,CAAC;AACrB,CAAC","file":"average.js","sourcesContent":["import { identity } from '../util/identity';\n\nexport function average(source: Iterable<number>, selector?: (x: number) => number): number;\nexport function average<T>(source: Iterable<T>, selector?: (x: T) => number): number;\n\n/**\n * Computes the average of a sequence of values from the sequence either from the sequence itself\n * or from the selector function.\n * @example\n * // Using non chained version\n * const result = average([1, 2, 3]);\n * const result = Ix.Iterable.of(1, 2, 3).average();\n * console.log(result);\n * @param {Iterable<any>} source A sequence of values to calculate the average of.\n * @param {function(x: any): number} [selector] A transform function to apply to each element.\n * @returns {number} The average of the sequence of values.\n */\nexport function average(source: Iterable<any>, selector: (x: any) => number = identity): number {\n let sum = 0;\n let count = 0;\n for (const item of source) {\n sum += selector(item);\n count++;\n }\n\n if (count === 0) {\n throw new Error('Empty collection');\n }\n\n return sum / count;\n}\n"]}
\No newline at end of file