Created
July 17, 2019 04:49
-
-
Save savagematt/f24729ddca893707c0a59202cd2d587d to your computer and use it in GitHub Desktop.
partitionMany
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {marbles} from "rxjs-marbles"; | |
export function partitions<T>( | |
source: ObservableInput<T>, | |
p1: ((value: T, index: number) => boolean), | |
): [Observable<T>, Observable<T>] ; | |
export function partitions<T>( | |
source: ObservableInput<T>, | |
p1: ((value: T, index: number) => boolean), | |
p2: ((value: T, index: number) => boolean), | |
): [Observable<T>, Observable<T>, Observable<T>] ; | |
export function partitions<T>( | |
source: ObservableInput<T>, | |
p1: ((value: T, index: number) => boolean), | |
p2: ((value: T, index: number) => boolean), | |
p3: ((value: T, index: number) => boolean), | |
): [Observable<T>, Observable<T>, Observable<T>, Observable<T>] ; | |
export function partitions<T>( | |
source: ObservableInput<T>, | |
p1: ((value: T, index: number) => boolean), | |
p2: ((value: T, index: number) => boolean), | |
p3: ((value: T, index: number) => boolean), | |
p4: ((value: T, index: number) => boolean), | |
): [Observable<T>, Observable<T>, Observable<T>, Observable<T>, Observable<T>] ; | |
export function partitions<T>( | |
source: ObservableInput<T>, | |
...predicates: ((value: T, index: number) => boolean)[] | |
): Observable<T>[] { | |
if(predicates.length===0) | |
throw new Error('No predicates provided'); | |
return predicates.reduce((result, p) => { | |
const last = result[result.length - 1]; | |
const partitioned = partition(last, p); | |
result.splice(result.length - 1, 1, ...partitioned); | |
return result; | |
}, [source] as Observable<T>[]); | |
} | |
describe('partitions', () => { | |
it('works just like partition for single predicate', marbles(m => { | |
const source = m.hot("^-1-2-3-4-5|"); | |
const [even, odd] = partitions(source, v => v % 2 == 0); | |
m.expect(odd).toBeObservable('^-1---3---5|'); | |
m.expect(even).toBeObservable('^---2---4--|'); | |
})); | |
it('multiple predicates create sequences by recursively partitioning the stream', marbles(m => { | |
const source = m.hot("^-1-2-3-4-5-6-7|"); | |
const [even__, divBy3, odd___] = partitions( | |
source, | |
v => v % 2 == 0, // split source into [even, odd] | |
v => v % 3 == 0 // split odd into [divisible by 3, rest of the odd numbers] | |
); | |
m.expect(even__).toBeObservable('^---2---4---6--|'); | |
m.expect(divBy3).toBeObservable('^-----3--------|'); | |
m.expect(odd___).toBeObservable('^-1-------5---7|'); | |
})) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment