From 98a6d0991df2a28366ab8f34098109a67257c235 Mon Sep 17 00:00:00 2001 From: Ben Lesh Date: Thu, 24 Sep 2020 22:56:48 -0500 Subject: [PATCH] refactor(count): Base off of `reduce`. BREAKING CHANGE: No longer passes `source` observable as a third argument to the predicate. That feature was rarely used, and of limited value. The workaround is to simply close over the source inside of the function if you need to access it in there. --- src/internal/operators/count.ts | 36 +++++++-------------------------- 1 file changed, 7 insertions(+), 29 deletions(-) diff --git a/src/internal/operators/count.ts b/src/internal/operators/count.ts index 5382a54a45..b21677b07f 100644 --- a/src/internal/operators/count.ts +++ b/src/internal/operators/count.ts @@ -1,8 +1,6 @@ /** @prettier */ -import { Observable } from '../Observable'; import { OperatorFunction } from '../types'; -import { operate } from '../util/lift'; -import { OperatorSubscriber } from './OperatorSubscriber'; +import { reduce } from './reduce'; /** * Counts the number of emissions on the source and emits that number when the * source completes. @@ -51,32 +49,12 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * @see {@link min} * @see {@link reduce} * - * @param {function(value: T, i: number, source: Observable): boolean} [predicate] A - * boolean function to select what values are to be counted. It is provided with - * arguments of: - * - `value`: the value from the source Observable. - * - `index`: the (zero-based) "index" of the value from the source Observable. - * - `source`: the source Observable instance itself. - * @return {Observable} An Observable of one number that represents the count as - * described above. - * @name count + * @param predicate A function that is used to analyze the value and the index and + * determine whether or not to increment the count. Return `true` to increment the count, + * and return `false` to keep the count the same. + * If the predicate is not provided, every value will be counted. */ -export function count(predicate?: (value: T, index: number, source: Observable) => boolean): OperatorFunction { - return operate((source, subscriber) => { - let index = 0; - let count = 0; - - source.subscribe( - new OperatorSubscriber( - subscriber, - (value) => (!predicate || predicate(value, index++, source)) && count++, - undefined, - () => { - subscriber.next(count); - subscriber.complete(); - } - ) - ); - }); +export function count(predicate?: (value: T, index: number) => boolean): OperatorFunction { + return reduce((count, value, i) => (!predicate || predicate(value, i) ? count + 1 : count), 0); }