Skip to content

Commit

Permalink
bugfix-min-max-async
Browse files Browse the repository at this point in the history
  • Loading branch information
uriva committed Nov 8, 2023
1 parent 033af8a commit 32220b3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
3 changes: 3 additions & 0 deletions src/reduce.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,6 @@ Deno.test("max call stack is not a limit on array size", () => {
}
assertEquals(max((x) => x)(bigArray), size - 1);
});

const _1: number = min((x: number) => x)([1, 2, 3, 4]);
const _2: number = min((x: number) => x)([1, 2, 3, 4]);
24 changes: 17 additions & 7 deletions src/reduce.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Func, ReturnTypeUnwrapped } from "./typing.ts";
import { AsyncFunction, Func, ReturnTypeUnwrapped } from "./typing.ts";

const reduceHelper = <
State,
Expand Down Expand Up @@ -33,14 +33,19 @@ export const reduce = <Function extends (state: any, element: any) => any>(

export const min = <F extends Func>(key: F) => (xs: Parameters<F>[0][]) =>
reduceHelper(
(s: Parameters<F>[0], x: Parameters<F>[0]) => {
(
s: Parameters<F>[0],
x: Parameters<F>[0],
): F extends AsyncFunction ? Promise<Parameters<F>[0]>
: Parameters<F>[0] => {
const keyS = key(s);
const keyX = key(x);
return (keyS instanceof Promise || keyX instanceof Promise)
return ((keyS instanceof Promise || keyX instanceof Promise)
? Promise.all([keyS, keyX]).then(([keyS, keyX]) => keyS < keyX ? s : x)
: key(s) < key(x)
? s
: x;
: x) as F extends AsyncFunction ? Promise<Parameters<F>[0]>
: Parameters<F>[0];
},
xs[0],
xs,
Expand All @@ -49,14 +54,19 @@ export const min = <F extends Func>(key: F) => (xs: Parameters<F>[0][]) =>

export const max = <F extends Func>(key: F) => (xs: Parameters<F>[0][]) =>
reduceHelper(
(s: Parameters<F>[0], x: Parameters<F>[0]) => {
(
s: Parameters<F>[0],
x: Parameters<F>[0],
): F extends AsyncFunction ? Promise<Parameters<F>[0]>
: Parameters<F>[0] => {
const keyS = key(s);
const keyX = key(x);
return (keyS instanceof Promise || keyX instanceof Promise)
return ((keyS instanceof Promise || keyX instanceof Promise)
? Promise.all([keyS, keyX]).then(([keyS, keyX]) => keyS < keyX ? x : s)
: key(s) < key(x)
? x
: s;
: s) as F extends AsyncFunction ? Promise<Parameters<F>[0]>
: Parameters<F>[0];
},
xs[0],
xs,
Expand Down

0 comments on commit 32220b3

Please sign in to comment.