Skip to content

Commit

Permalink
feat: add map reduce and maybe return a promise utility fn for change…
Browse files Browse the repository at this point in the history
… handlers (#125)
  • Loading branch information
nmathew98 committed Mar 5, 2024
1 parent 06d8689 commit a8a843f
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions packages/shared/src/use-qwery/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,31 @@
export * from "./types";

export const mapReduceMaybePromise =
<Fns extends Fn[]>(fns: Fns) =>
(...args: any[]): MaybePromise<SomeReturnsPromise<Fns[number]>> => {
const reduced = fns.reduce(
(acc, fn) => {
const result = fn(...args);

return {
hasPromise: acc.hasPromise || result instanceof Promise,
results: [...acc.results, result],
};
},
{ results: [] as any[], hasPromise: false },
);

if (reduced.hasPromise) {
return Promise.allSettled(reduced.results) as any;
}

return reduced.results as any;
};

type Fn = (...args: any[]) => any;
type SomeReturnsPromise<T> = T extends (...args: any[]) => infer R
? R extends Promise<any>
? true
: never
: never;
type MaybePromise<P> = P extends true ? Promise<void> : void;

0 comments on commit a8a843f

Please sign in to comment.