1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Add count() to iter

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton 2023-03-09 14:58:38 -05:00
parent 87cbfd1e39
commit d9721bfc75

View File

@ -14,6 +14,7 @@ interface Iterator<T> extends Iterable<T> {
flatMap<U>(fn: (val: T) => U[]): Iterator<U>; flatMap<U>(fn: (val: T) => U[]): Iterator<U>;
concat(src2: IterableIterator<T>): Iterator<T>; concat(src2: IterableIterator<T>): Iterator<T>;
join(sep?: string): string; join(sep?: string): string;
count(): T extends string ? { [P in T]?: number; } : never;
} }
export function chain<T>(src: IterableIterator<T>): Iterator<T> { export function chain<T>(src: IterableIterator<T>): Iterator<T> {
@ -26,6 +27,7 @@ export function chain<T>(src: IterableIterator<T>): Iterator<T> {
join: (sep) => join(src, sep), join: (sep) => join(src, sep),
collect: (fn) => fn(src), collect: (fn) => fn(src),
concat: (src2) => chain(concat(src, src2)), concat: (src2) => chain(concat(src, src2)),
count: () => countBy(src as unknown as Iterable<string>) as any,
[Symbol.iterator]: () => src, [Symbol.iterator]: () => src,
}; };
} }
@ -246,3 +248,15 @@ export function* concat<T>(...sources: IterableIterator<T>[]): IterableIterator<
} }
} }
} }
export function countBy<K extends string>(src: Iterable<K>): Partial<Record<K, number>> {
const result: Partial<Record<K, number>> = {};
for (const item of src) {
result[item] ??= 0;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
result[item]! += 1;
}
return result;
}