Last active
September 2, 2023 23:38
-
-
Save dmorosinotto/8959c773a7b4ff4e1243830ebaf60ae2 to your computer and use it in GitHub Desktop.
Some generic Utils: log, after, ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const LOGTYPES = ['log', 'info', 'warn', 'error'] as const; | |
interface LogType { | |
type: typeof LOGTYPES[number]; | |
} | |
export const log = (...args: Array<string | LogType | {}>) => { | |
let type: LogType['type'] = 'log'; | |
let prefix = [] as any[]; | |
let postfix = [] as any[]; | |
//@ts-ignore | |
const idx = args.findIndex((a) => LOGTYPES.includes(a?.type)); | |
if (~idx) { | |
[{ type }] = args.splice(idx, 1) as LogType[]; | |
prefix = args.splice(0, idx); | |
postfix = args; | |
} else prefix = args; //type='log', postfix=[] RIDONDANTE | |
return (value?: any) => | |
console[type]( | |
new Date().toISOString().substring(11), | |
...prefix, | |
value, | |
...postfix | |
) as unknown as false; | |
}; | |
export function after<F extends (...args: any) => any>( | |
time: number, | |
fn: F, | |
...args: Parameters<F> | |
): Promise<ReturnType<F>> { | |
return new Promise(function (resolve, reject) { | |
setTimeout( | |
function (...args: Parameters<F>) { | |
try { | |
resolve(fn(...Array.from(args))); | |
} catch (err) { | |
reject(err); | |
} | |
}, | |
time, | |
...Array.from(args) | |
); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { log, after } from "./my-utils"; | |
after(1500, (a, b) => log('+')(a + b) || a * b, 2, '3') //infer a:number, b:string + check correct number of params after fn | |
.then((ret) => console.warn({ ret })) //infer ret: number | |
.catch(log({type: 'error'})); //eventually console.error | |
const answer = await after(500, ()=>42); //infer answer: number | |
log("What does", {type: 'info'}, "mean in the meaning of life?")(answer); | |
after(1000, log({type:'warn'}), "The answer to life, the universe and everything!"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment