Last active
February 29, 2024 17:39
-
-
Save matsuby/4fc2e6e2c7e3c41cb5e21e003128856d to your computer and use it in GitHub Desktop.
fetcher cash tag creator.
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
type KV = Record<string, any>; | |
type MyParameters<F> = F extends (...args: infer P) => unknown | |
? P extends [infer A] | |
? A extends KV | |
? KV | |
: [A] | |
: P | |
: never; | |
function cashTagFactory<F extends (...params: any[]) => unknown>( | |
fetcher: F, | |
): (params: MyParameters<F>) => string { | |
return (params) => { | |
let kv: Record<string, any> = params; | |
if (Array.isArray(params)) { | |
kv = Object.fromEntries(params.map((v, i) => [`p${i}`, `${v}`])); | |
} | |
return `${new URLSearchParams({ _fn: fetcher.name, ...kv })}`; | |
}; | |
} | |
const f1 = ({ name, age }: { name: string; age: number }) => `${name}:${age}`; | |
const f2 = (name: string, age: number) => `${name}:${age}`; | |
f1.getTag = cashTagFactory(f1); | |
f2.getTag = cashTagFactory(f2); | |
console.log(f1.getTag({ name: "matsuby", age: 32 })); // "_fn=f1&name=matsuby&age=32" | |
console.log(f2.getTag(["matsuby", 32])); // "_fn=f2&p0=matsuby&p1=32" | |
// TODO: getTag can't accepet positional arguments😕 | |
// console.log(f2.getTag("matsuby", 32)); // Expected 1 arguments, but got 2. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment