added filling and reduction to iterators

This commit is contained in:
Matthieu Jolimaitre 2024-10-08 12:15:58 +02:00
parent 0b464ba8a3
commit d90cae3651
2 changed files with 19 additions and 1 deletions

View file

@ -2,7 +2,7 @@
export type { Arr, ClassOf, Constructible, Function, InstanceOf, KeyOfType, Tail } from "./lib/types.ts";
// functions
export { all, chunk, enumerate, filter, filter_map, it, Iter, map, window, zip } from "./lib/iter.ts";
export { all, chunk, enumerate, fill, filter, filter_map, fold, it, Iter, map, window, zip } from "./lib/iter.ts";
export { log_from, next, split_promise, wait } from "./lib/utils.ts";
// Structures

View file

@ -67,6 +67,16 @@ export function* window<T>(iter: Iterable<T>, size: number, incomplete = false):
}
}
export function* fill<I, O>(iter: Iterable<I>, value: O) {
for (const _item of iter) yield value;
}
export function fold<I, O>(iter: Iterable<I>, init: O, reduction: (item: I, acc: O) => O) {
let accumulator = init;
for (const item of iter) accumulator = reduction(item, accumulator);
return accumulator;
}
export class Iter<T> {
iter;
[Symbol.iterator] = () => this.iter[Symbol.iterator]();
@ -121,6 +131,14 @@ export class Iter<T> {
all(predicate: (item: T) => boolean) {
return all(this, predicate);
}
fill<O>(value: O) {
return fill(this, value);
}
fold<O>(init: O, reduction: (item: T, acc: O) => O) {
return fold(this, init, reduction);
}
}
Deno.test("test_comon", async () => {