data-collectors
Version:
A collection of composable reduction operations for arbitrary streams of values
40 lines (31 loc) • 1.48 kB
text/typescript
import { Collector, BaseCollector, collect } from "../collector";
import { Mapper } from "../collections/groupingBy";
import { toArray } from "../collections/toArray";
export class FlatMappingCollector<T, U, A, R> extends BaseCollector<T, A, R> {
protected mapper : Mapper<T, Iterable<U>>;
protected collector : Collector<U, A, R>;
constructor ( mapper : Mapper<T, Iterable<U>>, collector : Collector<U, A, R> ) {
super();
this.mapper = mapper;
this.collector = collector;
}
supply () : A {
return this.collector.supply();
}
accumulate ( container : A, item : T ) : void {
for ( let subItem of this.mapper( item ) ) {
this.collector.accumulate( container, subItem );
}
}
combine ( container1 : A, container2 : A ) : A {
return this.collector.combine( container1, container2 );
}
finish ( container : A ) : R {
return this.collector.finish( container );
}
}
export function flatMapping<T, U> ( mapper : Mapper<T, Iterable<U>> ) : Collector<T, U[], U[]>;
export function flatMapping<T, U, A, R> ( mapper : Mapper<T, Iterable<U>>, collector ?: Collector<U, A, R> ) : Collector<T, A, R>;
export function flatMapping<T, U, A, R> ( mapper : Mapper<T, Iterable<U>>, collector ?: Collector<U, A, R> ) : Collector<T, A | U[], R | U[]> {
return new FlatMappingCollector( mapper, collector || toArray() as any );
}