mirror of
https://github.com/nestriness/nestri.git
synced 2026-09-24 03:28:18 +03:00
feat: Sync to OSS repo
This commit is contained in:
30
packages/core/src/utils/combine-promises.ts
Normal file
30
packages/core/src/utils/combine-promises.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
type UnwrapPromise<P extends unknown> = P extends PromiseLike<infer V> ? V : P;
|
||||
|
||||
type Input = Record<string | number | symbol, unknown>;
|
||||
|
||||
type Result<Obj extends Input> = {
|
||||
[P in keyof Obj]: UnwrapPromise<Obj[P]>;
|
||||
};
|
||||
|
||||
export default function combinePromises<Obj extends Input>(obj: Obj): Promise<Result<Obj>> {
|
||||
if (obj === null) {
|
||||
return Promise.reject(new Error('combinePromises does not handle null argument'));
|
||||
}
|
||||
if (typeof obj !== 'object') {
|
||||
return Promise.reject(
|
||||
new Error(`combinePromises does not handle argument of type ${typeof obj}`)
|
||||
);
|
||||
}
|
||||
|
||||
const keys = Object.keys(obj);
|
||||
|
||||
// not using async/await on purpose, otherwise lib outputs large _asyncToGenerator code in dist
|
||||
return Promise.all(Object.values(obj)).then((values) => {
|
||||
const result: any = {};
|
||||
values.forEach((v, i) => {
|
||||
//@ts-expect-error this is NEVER undefined
|
||||
result[keys[i]] = v;
|
||||
});
|
||||
return result;
|
||||
});
|
||||
}
|
||||
18
packages/core/src/utils/memo.ts
Normal file
18
packages/core/src/utils/memo.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export function memo<T>(fn: () => T, cleanup?: (input: T) => Promise<void>) {
|
||||
let value: T | undefined;
|
||||
let loaded = false;
|
||||
|
||||
const result = (): T => {
|
||||
if (loaded) return value as T;
|
||||
loaded = true;
|
||||
value = fn();
|
||||
return value as T;
|
||||
};
|
||||
result.reset = async () => {
|
||||
if (cleanup && value) await cleanup(value);
|
||||
loaded = false;
|
||||
value = undefined;
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
Reference in New Issue
Block a user