From 92b484b1e02054be8d366151e099d9fda6efe625 Mon Sep 17 00:00:00 2001 From: kazuya kawaguchi Date: Wed, 4 Oct 2023 18:35:46 +0900 Subject: [PATCH 1/5] feat: type utilites for unicode language id --- src/locale.ts | 230 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 230 insertions(+) create mode 100644 src/locale.ts diff --git a/src/locale.ts b/src/locale.ts new file mode 100644 index 0000000..f041299 --- /dev/null +++ b/src/locale.ts @@ -0,0 +1,230 @@ +export interface UnicodeLocaleId { + lang: UnicodeLanguageId + extensions: Array< + UnicodeExtension | TransformedExtension | PuExtension | OtherExtension + > +} + +export interface UnicodeLanguageId { + lang: string + script?: string + region?: string + variants: string[] +} + +// ----- + +type IsNever = [T] extends [never] ? true : false +type Split = string extends S ? string[] + : S extends `${infer A}${SEP}${infer B}` + ? [A, ...(B extends '' ? [] : Split)] + : SEP extends '' ? [] + : [S] +type Shift = T extends [unknown, ...infer U] ? U : never +type First = T extends [infer A, ...infer rest] ? A : never +type Last = [unknown, ...T][T['length']] +type Length = T['length'] +type IsEqual = (() => T extends X ? 1 : 2) extends + (() => T extends Y ? 1 : 2) ? true : false +type Push = [...T, U] +type Includes = IsEqual extends + true ? true + : Value extends [Value[0], ...infer rest] ? Includes + : false +type UnionToIntersection = ( + U extends unknown ? (arg: U) => 0 : never +) extends (arg: infer I) => 0 ? I + : never +type LastInUnion = UnionToIntersection< + U extends unknown ? (x: U) => 0 : never +> extends (x: infer L) => 0 ? L + : never +type UnionToTuple> = [U] extends [never] ? [] + : [...UnionToTuple>, Last] +type StrintToUnion = T extends `${infer Letter}${infer Rest}` + ? Letter | StrintToUnion + : never +type StringToTuple = UnionToTuple> + +type Alphabets = + | 'a' + | 'b' + | 'c' + | 'd' + | 'e' + | 'f' + | 'g' + | 'h' + | 'i' + | 'j' + | 'k' + | 'l' + | 'm' + | 'n' + | 'o' + | 'p' + | 'q' + | 'r' + | 's' + | 'v' + | 'w' + | 'y' + | 'z' + +type Numbers = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' + +type ParseUnicodeLanguageId< + T extends string, + S extends unknown[] = Split, + Lang extends unknown[] = ParseLangSubtag>, + Rest1 extends unknown[] = Shift, + Script extends unknown[] = ParseScriptSubtag>, + Rest2 extends unknown[] = Shift, + Region extends unknown[] = ParseRegionSubtag>, + Rest3 extends unknown[] = Shift, + Variants extends { variants: string[]; error?: string } = ParseVariantsSubtag< + Rest3 + >, +> = [ + { + lang: First + script: First