C언어에는 함수 printf가 있다: 이 함수는 포매팅이 된 무언가를 프린트하도록 한다.
포맷은 다음과 같다:
printf("The result is %d.", 42);
이 챌린지는 문자열을 입력받아 %d나 %f 같은 플레이스 홀더 포맷을 추출한다. 예를 들어, 만약 입력 문자열이 "The result is %d."라면, 파싱 결과는 튜플 ['dec']이다.
There is a function in C language: printf. This function allows us to print something with formatting. Like this:
printf("The result is %d.", 42);
This challenge requires you to parse the input string and extract the format placeholders like %d and %f. For example, if the input string is "The result is %d.", the parsed result is a tuple ['dec'].
type ParsePrintFormat<S extends string>=
S extends `${infer First}${infer Rest}`?
First extends '%'?
Rest extends `${infer Target}${infer RestRest}`?
Target extends keyof ControlsMap?[ControlsMap[Target],...ParsePrintFormat<RestRest>]:
ParsePrintFormat<RestRest>
:ParsePrintFormat<Rest>
:ParsePrintFormat<Rest>
:[]
우선 특이 사례를 보자.
%%d의 값은 []이고 %%%d의 값은 ['dec']이다. 아마 %뒤에 있는 값이 controlsMap에 없다면 해당 플레이스 홀더를 무시하는 것으로 보인다.
이를 감안하여 문제를 해결하였다.
재귀적으로 문자열을 확인해나간다.
첫 문자가 %고 두 번째 문자가 keyof ControlsMap이면 해당 문자를 배열에 넣어 뒤의 재귀 값과 함께 반환한다.
첫 문자가 %고 두 번째 문자가 keyof ControlsMap가 아니면 두 문자를 무시하고 파싱을 이어나간다.
그것이 아니라면 첫 문자를 제외한 나머지 값에 대한 파싱을 이어나간다.
마지막에는 빈 배열을 반환한다.