UNPKG

romanize-string

Version:

A fully typed, general-purpose utility for unidirectional string transliteration (non-Latin script => Latin script).

57 lines (56 loc) 2.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HangulSyllable = void 0; class HangulSyllable { static SBase = 0xac00; static LBase = 0x1100; static VBase = 0x1161; static TBase = 0x11a7; static LCount = 19; static VCount = 21; static TCount = 28; static NCount = HangulSyllable.VCount * HangulSyllable.TCount; // 588 static SCount = HangulSyllable.LCount * HangulSyllable.NCount; // 11,172 syllable; choseong; jungseong; jongseong; constructor(syllable) { if (syllable.length !== 1 || syllable.charCodeAt(0) < 0xac00 || syllable.charCodeAt(0) > 0xd7a3) throw new Error(`Invalid Hangul Syllable "${syllable}"`); this.syllable = syllable; const { choseong, jungseong, jongseong } = this.map(); this.choseong = choseong; this.jungseong = jungseong; this.jongseong = jongseong; } // https://en.wikipedia.org/wiki/Korean_language_and_computers#Hangul_in_Unicode // [(initial) × 588 + (medial) × 28 + (final)] + 44032 // See https://www.unicode.org/versions/Unicode13.0.0/ch03.pdf#G24646 // for official documentation on the arithmetic decomposition mapping of Hangul syllables map() { const code = this.syllable.charCodeAt(0); const SIndex = code - HangulSyllable.SBase; const LIndex = Math.floor(SIndex / HangulSyllable.NCount); const VIndex = Math.floor((SIndex % HangulSyllable.NCount) / HangulSyllable.TCount); const TIndex = SIndex % HangulSyllable.TCount; const LPart = String.fromCharCode(HangulSyllable.LBase + LIndex); const VPart = String.fromCharCode(HangulSyllable.VBase + VIndex); const TPart = TIndex === 0 ? "" : String.fromCharCode(HangulSyllable.TBase + TIndex); return { choseong: LPart, jungseong: VPart, jongseong: TPart }; } get initial() { return this.choseong; } get medial() { return this.jungseong; } get final() { return this.jongseong; } } exports.HangulSyllable = HangulSyllable;