import { Observable as ObservableT, Subscription } from './index' import Observable from './observable' /** * Filter an observable based on a predicate * * {@link filter} will execute `predicate` for every value emitted from `Observable`. If `predicate` returns * `false`, then the output `Observable` won't emit that `T`. If `predicate` returns `true` then the ouput * `Observable` will emit that `T`. * * @example Marble diagram with a filter * * // predicate p: x => x % 2 == 0 * // source s: |--1--2--3--4--5--6--| * // filter(p, s): |-----2-----4-----6--| * * @param {ObservableT} source source observable that will be filtered * @param {(item: T) => boolean} predicate the filter predicate * @returns {ObservableT} filtered source observable by predicate */ export default function filter( source: ObservableT, predicate: (item: T) => boolean ): ObservableT { return new Observable( ({ complete, error, next }): Subscription => source.subscribe({ complete, error, next: (value): false | void => predicate(value) && next(value) }) ) }