Skip to content

Instantly share code, notes, and snippets.

@kana-sama
Last active October 21, 2023 12:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kana-sama/e92f5df4f8ba7f57ab5b097a53ff996d to your computer and use it in GitHub Desktop.
Save kana-sama/e92f5df4f8ba7f57ab5b097a53ff996d to your computer and use it in GitHub Desktop.
// >> inter(["a", "b", "c"], "d")
// ["a", "d", "b", "d", "c"]
function inter<T>(xs: T[], s: T): T[] {
return xs.flatMap((x, i) => i === xs.length - 1 ? [x] : [x, s]);
}
// >> extractTok("ab,cd,ef", ",")
// ["ab", ",", "cd", ",", "ef"]
function extractTok(tok: string, template: string): string[] {
return inter(tok.split(template), template);
}
// >> lex("a %d b %s c")
// ["a ", "%d", " b ", "%s", " c"]
function lex(format: string): string[] {
return [format]
.flatMap(_ => extractTok(_, "%d"))
.flatMap(_ => extractTok(_, "%s"));
}
// >> parse<"a %d b %s c">
// [number, string]
type parse<s extends string> =
s extends `%d${infer s}` ? [d: number, ...parse<s>] :
s extends `%s${infer s}` ? [s: string, ...parse<s>] :
s extends `${infer _}${infer s}` ? parse<s> :
s extends `` ? [] :
never;
// >> printf("Hello %s (id = %d)", "kana", 123)
// "Hello kana (id = 123)"
function printf<const Format extends string>(format: Format, ...args: parse<Format>) {
let result = "";
const arg = args[Symbol.iterator]();
for (const tok of lex(format)) {
switch (tok) {
case "%d":
case "%s":
result += arg.next().value;
break;
default:
result += tok;
}
}
return result;
}
console.clear();
console.log(inter(["a", "b", "c"], "d"));
console.log(extractTok("ab,cd,ef", ","));
console.log(lex("a %d b %s c"));
console.log(printf("Hello %s (id = %d)", "kana", 123));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment