Skip to content

Commit

Permalink
chore(pattern): enhance types syntax/readability (#275)
Browse files Browse the repository at this point in the history
  • Loading branch information
fraxken authored Jul 2, 2024
1 parent 9663952 commit 7ebb58d
Showing 1 changed file with 23 additions and 17 deletions.
40 changes: 23 additions & 17 deletions src/pattern/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,41 @@
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-unused-vars */

type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {};
type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};

type ConvertEmptyRecord<T, R = string> = T extends Record<string, never> ? R : T;

type TupleToObject<T extends Array<string>> = {
[key in ExtractPattern<T[number]>]: string
};

type Split<S extends string, D extends string> =
string extends S ? Array<string> :
string extends S ? string[] :
S extends "" ? [] :
S extends `${infer T}${D}${infer U}` ? [`${T}${D}`, ...Split<U, D>] : [S];

type Trim<T> = T extends `${" "}${infer U}` ?
Trim<U> : T extends `${infer U}${" "}` ? Trim<U> : T;
type Trim<S extends string> =
S extends ` ${infer U}` ? Trim<U> :
S extends `${infer U} ` ? Trim<U> :
S;

type Concat<T extends Array<string>> = T extends [
infer F extends string,
...infer R extends Array<string>
] ? `${F} ${Concat<R>}` : "";
type Concat<T extends string[]> = T extends [infer F extends string, ...infer R extends string[]]
? `${F} ${Concat<R>}`
: "";

type ArrayToString<T extends LokiPatternType> =
T extends Array<string> ? Concat<T> :
T extends ReadonlyArray<string> ? Concat<[...T]> : T;
T extends string[] ? Concat<T> :
T extends readonly string[] ? Concat<[...T]> :
T;

type ExtractPattern<Pattern extends string> =
Pattern extends `${infer _}<${infer Name}>${infer _}` ?
(Name extends "_" ? never : Trim<Name>)
:
never;

type TupleToObject<T extends string[]> = {
[key in ExtractPattern<T[number]>]: string;
};

type ExtractPattern<Pattern extends string> = Pattern extends `${infer _}<${infer Name}>${infer _}` ?
Name extends "_" ? never : Trim<Name> : never;
export type LokiPatternType = string | string[] | readonly string[];

export type LokiPatternType = string | Array<string> | ReadonlyArray<string>;
export type LokiLiteralPattern<T extends LokiPatternType> = ConvertEmptyRecord<Simplify<
TupleToObject<Split<ArrayToString<T>, ">">>
>>;

0 comments on commit 7ebb58d

Please sign in to comment.