Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const foo1 = (a: string): number =>
{
console.log('foo1', {a});
return a.length;
}
const foo2 = (a: string, b: number): number => {
console.log('foo2', {a, b});
return a.length + b;
}
const foo3 = (a: string, b: number, c: string): string => {
console.log('foo3', {a, b, c});
return `${a} | ${b} | ${c}`;
}
function someMagicThingyExtra(result: any): any {
console.log('kksksk', {result});
return result;
}
//https://stackoverflow.com/questions/59212683/typescript-wrapping-functions-while-preserving-signatures
function wrapOneX<T extends (...args: any) => any>(fn: T): T {
return ((...args: Parameters<typeof fn>) => {
console.log('wrapOneX', args);
// return someMagicThingyExtra(fn(args))
return fn.apply(window, args) //WINDOW as this ????
}) as T
}
const wx1 = wrapOneX(foo1);
const wx2 = wrapOneX(foo2);
const wx3 = wrapOneX(foo3);
console.log("wx1", wx1("asdf1234"));
console.log("wx2", wx2("kkk", 4));
console.log("wx3", wx3("kkk", 4, "xxx"));
//https://stackoverflow.com/questions/62521955/how-to-create-a-generic-wrapper-function-that-preserves-signature-and-has-a-simi
type AnyFunction = (...args: any[]) => any;
const wrapAAA = function <T extends AnyFunction>(func: T): (...parameters: Parameters<T>) => ReturnType<T> | void {
// const run = Math.random() % 2 > 0
const wrapped = (...args: Parameters<T>): ReturnType<T> | void => {
// if (run) {
return func(args)
// }
}
return wrapped
}
const wa1 = wrapAAA(foo1);
const wa2 = wrapAAA(foo2);
const wa3 = wrapAAA(foo3);
console.log("wa1", wa1("sdfew78"));
console.log("wa2", wa2("kkk", 4));
console.log("wa3", wa3("kkk", 4, "xxx"));
function wrapperZ<Args extends any[], Return>(
operation: (...operationParameters: Args) => Return,
...parameters: Args
): Return {
console.log(`outer `, {...parameters});
return operation(...parameters);
}
console.log("wz1", wrapperZ(foo1, "sss"));
console.log("wz2", wrapperZ(foo2, "fff", 10));
console.log("wz3", wrapperZ(foo3, "fff", 455, "hhh"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment