1
0
Files
sequence-js/src/collector/index.ts
Herve BECHER 0fd0e3bada sync
2025-05-24 12:11:44 +02:00

65 lines
2.8 KiB
TypeScript

import { Converter } from "../types.js";
import { SimpleCollector, ToArrayCollector, ToObjectCollector, ToMapCollector, ToSetCollector, JoinCollector, SumCollector, BigIntSumCollector, AverageCollector, BigIntAverageCollector, ToObjectListCollector, ToMapListCollector } from "./impl.js";
import { Collector } from "./types.js";
export function create<TElement, TAccumulator, TResult>(initialize: () => TAccumulator, accumulate: (accumulator: TAccumulator, element: TElement) => void,
finalize: (accumulator: TAccumulator) => TResult): Collector<TElement, TAccumulator, TResult> {
return new SimpleCollector(initialize, accumulate, finalize);
}
const toArrayCollector = new ToArrayCollector<any>();
export function toArray<TElement>(): Collector<TElement, any, TElement[]> {
return toArrayCollector;
}
export function toObject<TElement, TKey extends PropertyKey, TValue>(keySelector: Converter<TElement, TKey>, valueSelector: Converter<TElement, TValue>): Collector<TElement, any, Record<TKey, TValue>> {
return new ToObjectCollector<TElement, TKey, TValue>(keySelector, valueSelector);
}
export function toObjectList<TElement, TKey extends PropertyKey, TValue>(keySelector: Converter<TElement, TKey>, valueSelector: Converter<TElement, TValue>): Collector<TElement, any, Record<TKey, TValue[]>> {
return new ToObjectListCollector<TElement, TKey, TValue>(keySelector, valueSelector);
}
export function toMap<TElement, TKey, TValue>(keySelector: Converter<TElement, TKey>, valueSelector: Converter<TElement, TValue>): Collector<TElement, any, Map<TKey, TValue>> {
return new ToMapCollector<TElement, TKey, TValue>(keySelector, valueSelector);
}
export function toMapList<TElement, TKey, TValue>(keySelector: Converter<TElement, TKey>, valueSelector: Converter<TElement, TValue>): Collector<TElement, any, Map<TKey, TValue[]>> {
return new ToMapListCollector<TElement, TKey, TValue>(keySelector, valueSelector);
}
const toSetCollector = new ToSetCollector<any>();
export function toSet<TElement>(): Collector<TElement, any, Set<TElement>> {
return toSetCollector;
}
export function join(delimiter?: string, prefix?: string, suffix?: string): Collector<any, any, string> {
return new JoinCollector(delimiter, prefix, suffix);
}
const sumCollector = new SumCollector();
export function sum(): Collector<number, any, number> {
return sumCollector;
}
const bigintSumCollector = new BigIntSumCollector();
export function bigintSum(): Collector<bigint, any, bigint> {
return bigintSumCollector;
}
const averageCollector = new AverageCollector();
export function average(): Collector<number, any, number> {
return averageCollector;
}
const bigintAverageCollector = new BigIntAverageCollector();
export function bigintAverage(): Collector<bigint, any, bigint> {
return bigintAverageCollector;
}