added folding to iterators
This commit is contained in:
parent
d90cae3651
commit
57e3126702
2 changed files with 31 additions and 4 deletions
16
src/lib.ts
16
src/lib.ts
|
@ -2,7 +2,21 @@
|
|||
export type { Arr, ClassOf, Constructible, Function, InstanceOf, KeyOfType, Tail } from "./lib/types.ts";
|
||||
|
||||
// functions
|
||||
export { all, chunk, enumerate, fill, filter, filter_map, fold, it, Iter, map, window, zip } from "./lib/iter.ts";
|
||||
export {
|
||||
all,
|
||||
chunk,
|
||||
enumerate,
|
||||
fill,
|
||||
filter,
|
||||
filter_map,
|
||||
fold,
|
||||
it,
|
||||
Iter,
|
||||
map,
|
||||
reduce,
|
||||
window,
|
||||
zip,
|
||||
} from "./lib/iter.ts";
|
||||
export { log_from, next, split_promise, wait } from "./lib/utils.ts";
|
||||
|
||||
// Structures
|
||||
|
|
|
@ -71,12 +71,21 @@ 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) {
|
||||
export function reduce<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 function fold<T>(iter: Iterable<T>, reduction: (first: T, next: T) => T) {
|
||||
let accumulator = undefined as T | undefined, passed_first = false;
|
||||
for (const item of iter) {
|
||||
if (passed_first) accumulator = reduction(accumulator!, item);
|
||||
else accumulator = item, passed_first = true;
|
||||
}
|
||||
return accumulator;
|
||||
}
|
||||
|
||||
export class Iter<T> {
|
||||
iter;
|
||||
[Symbol.iterator] = () => this.iter[Symbol.iterator]();
|
||||
|
@ -136,8 +145,12 @@ export class Iter<T> {
|
|||
return fill(this, value);
|
||||
}
|
||||
|
||||
fold<O>(init: O, reduction: (item: T, acc: O) => O) {
|
||||
return fold(this, init, reduction);
|
||||
fold(reduction: (first: T, next: T) => T) {
|
||||
return fold(this, reduction);
|
||||
}
|
||||
|
||||
reduce<O>(init: O, reduction: (item: T, acc: O) => O) {
|
||||
return reduce(this, init, reduction);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue