Skip to content

Instantly share code, notes, and snippets.

@ericdmoore
Last active April 22, 2021 02:43
Show Gist options
  • Save ericdmoore/4191d5a8a21f8e8825a5b942ebf60338 to your computer and use it in GitHub Desktop.
Save ericdmoore/4191d5a8a21f8e8825a5b942ebf60338 to your computer and use it in GitHub Desktop.
// vanilla version of TS (from esbiuild)
const {isArray} = Array;
const isPrim = (i) => {
const types = ["string", "number", "boolean", "function", "undefined", "bigint", "symbol"];
return types.some((tStr) => typeof i === tStr);
};
const isObject = (i) => {
return !isPrim(i) && !isArray(i);
};
export const PromiseResolve = async (promisedInputObj) => {
const resolvedInput = await promisedInputObj;
const keys = Object.keys(resolvedInput);
const vals = await Promise.all(Object.values(j));
return vals.reduce(async (prior, val, i) => ({
...await prior,
[keys[i]]: isObject(val) ? await PromiseResolve(val) : val
}), Promise.resolve({}));
};
export default PromiseResolve;
// #region interfaces
type PromiseOr<T> = Promise<T> | T
type DictUnknowns = {[str:string]:unknown}
// #endregion interfaces
const { isArray } = Array
const isPrim = (i:unknown) => {
const types = ['string', 'number', 'boolean', 'function', 'undefined', 'bigint', 'symbol']
// eslint-disable-next-line valid-typeof
return types.some(tStr => typeof i === tStr)
}
const isObject = (i:unknown) : i is {[s:string]:unknown} => {
return !isPrim(i) && !isArray(i)
}
/**
*
* @param promisedInputObj
*/
export const PromiseResolve = async (promisedInputObj: PromiseOr<DictUnknowns>): Promise<DictUnknowns> => {
const resolvedInput = await promisedInputObj
const keys = Object.keys(resolvedInput)
const vals = await Promise.all(Object.values(resolvedInput))
return vals.reduce(async (prior:Promise<DictUnknowns>, val, i) => ({
...(await prior),
[keys[i]]: isObject(val)
? await PromiseResolve(val as PromiseOr<DictUnknowns>)
: val
}), Promise.resolve({}) as Promise<DictUnknowns>)
}
export default PromiseResolve
@ericdmoore
Copy link
Author

I wish :

  • I could think through the types better.
  • this was included in a lodash or other widely used package or backed in to Promise.resolve({}, {recursive: true})
  • that TC39 would take up a way to define a hashmap in JS directly - as opposed to is not Array && is not Primitive - maybe there's a way and I just need to ask someone smarter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment