Skip to content

Commit

Permalink
docs: add jsdoc for reduceLazy
Browse files Browse the repository at this point in the history
  • Loading branch information
Phryxia committed Feb 17, 2024
1 parent 57e3e8c commit cd3cbf6
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 6 deletions.
44 changes: 44 additions & 0 deletions src/Lazy/reduceLazy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,50 @@ type InferCarrier<T> = T extends AsyncIterable<infer R>
// DO NOT change the order of signatures prematurely.
// See `reduceLazy.test.ts` for the reason

/**
* High order functional version of `reduce`, which behaves identical to it.
*
* @param f Reducer function `(acc, value) => acc`. It can be both synchronous and asynchronous.
* @param seed Initial value. Note that if the type of `acc` and `value` differ, `seed` must be given.
*
* @example
* Type must be provided for stand alone call.
*
* ```ts
* const reduce = reduceLazy((a: number, b: number) => a + b, 5)
*
* reduce([1, 2, 3]) // number
* reduce(toAsync([1, 2, 3])) // Promise<number>
* ```
*
* Fit perfectly with `pipe`
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* reduceLazy((a, b) => a + b, 5)
* ); // 15
* ```
*
* You can use asynchronous callback
*
* ```ts
* await pipe(
* [1, 2, 3, 4],
* reduceLazy(async (a, b) => a + b, 5)
* ); // 15
* ```
*
* `AsyncIterable` doesn't matter.
*
* ```ts
* await pipe(
* [1, 2, 3, 4],
* toAsync,
* reduceLazy((a, b) => a + b, 5)
* ); // 15
* ```
*/
function reduceLazy<T extends Iterable<unknown> | AsyncIterable<unknown>, Acc>(
f: SyncReducer<Acc, IterableInfer<T>> | AsyncReducer<Acc, IterableInfer<T>>,
seed: Acc,
Expand Down
11 changes: 5 additions & 6 deletions src/reduce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,8 @@ async function async<T, Acc>(
* ); // 26
* ```
*
* Currently, type with explicit seed form can't be inferred properly due to the limitation of typescript.
* But you can still use mostly with @ts-ignore flag. For more information please visit issue.
*
* {@link https://github.com/marpple/FxTS/issues/239 | #related issue}
*
* For backward compatibility, `reduce` can support partial lazy form.
* You may want to use `reduceLazy` to use `seed`.
*
* ```ts
* await pipe(
Expand Down Expand Up @@ -190,7 +187,9 @@ function reduce<T extends Iterable<unknown> | AsyncIterable<unknown>, Acc>(
});
}

throw new TypeError("'iterable' must be type of Iterable or AsyncIterable");
throw new TypeError(
"'iterable' must be type of Iterable or AsyncIterable. Are you looking for 'reduceLazy'?",
);
}

if (isIterable(iterable)) {
Expand Down

0 comments on commit cd3cbf6

Please sign in to comment.