UNPKG

romanize-string

Version:

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

57 lines (56 loc) 1.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.romanize = romanize; const revised_js_1 = require("./constants/revised.js"); const decompose_hangul_js_1 = require("./lib/decompose-hangul.js"); const is_hangul_js_1 = require("./lib/is-hangul.js"); const tree = new is_hangul_js_1.HangulTree(); function separate(hangul) { if (!tree.isHangul(hangul)) { throw new Error("Not a Hangul string"); } const chars = hangul.split("").reduce((list, char) => { const result = tree.search(char.charCodeAt(0)); const block = result.length === 1 ? result[0].value : null; switch (block) { case "HANGUL_SYLLABLES": const syllable = new decompose_hangul_js_1.HangulSyllable(char); const { initial, medial, final } = syllable; if (final !== "") { return list.concat([initial, medial, final]); } return list.concat([initial, medial]); case null: default: return list.concat([char]); } }, []); return chars; } function convert(chars, system) { let res = ""; for (let i = 0; i < chars.length; i++) { if (chars[i] in system) { const c = chars[i]; if (system[c].next && i + 1 < chars.length && chars[i + 1] in system) { const nextC = chars[i + 1]; if (nextC in system[c].next) { const nextInitial = nextC; res += system[c].next[nextInitial]; i++; continue; } } res += system[c].base; continue; } res += chars[i]; } return res; } function romanize(hangul) { const chars = separate(hangul); return convert(chars, revised_js_1.REVISED_ROMANIZATION_OF_KOREAN); }