Skip to content

Instantly share code, notes, and snippets.

@saschanaz
Created March 7, 2019 14:47
Show Gist options
  • Save saschanaz/a840b842e5f30ef6d1b3c7f110152c8a to your computer and use it in GitHub Desktop.
Save saschanaz/a840b842e5f30ef6d1b3c7f110152c8a to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
html, body {
margin: 0;
height: 100%;
}
#textarea {
width: 800px;
height: 100%;
}
</style>
</head>
<body>
<textarea id="textarea">어디거쳐왔ㄷㅏ는ㄱㅓㄹ 정ㅎㅘㄱ히알수있ㅇㅡㅁ</textarea>
<button id="button">Go</button>
<script>
button.addEventListener("click", () => {
textarea.value = convert(textarea.value);
})
const ChoSeong = [
0x3131, 0x3132, 0x3134, 0x3137, 0x3138, 0x3139,
0x3141, 0x3142, 0x3143, 0x3145, 0x3146, 0x3147,
0x3148, 0x3149, 0x314a, 0x314b, 0x314c, 0x314d, 0x314e
];
const JungSeong = [
0x314f, 0x3150, 0x3151, 0x3152, 0x3153, 0x3154,
0x3155, 0x3156, 0x3157, 0x3158, 0x3159, 0x315a,
0x315b,0x315c, 0x315d, 0x315e, 0x315f, 0x3160,
0x3161, 0x3162, 0x3163
];
const JongSeong = [
0x0000, 0x3131, 0x3132, 0x3133, 0x3134,0x3135,
0x3136, 0x3137, 0x3139, 0x313a, 0x313b, 0x313c,
0x313d, 0x313e, 0x313f, 0x3140, 0x3141, 0x3142,
0x3144, 0x3145, 0x3146, 0x3147, 0x3148, 0x314a,
0x314b, 0x314c, 0x314d, 0x314e
];
function convert(str) {
const array = [];
let cho = 0;
let jung = 0;
let jong = 0;
for (const char of str) {
const code = char.codePointAt(0);
if (code >= 0x3131 && code <= 0x314e) { // ja
if (cho && !jung) {
array.push(String.fromCodePoint(cho));
initialize();
}
else if (jong) {
array.push(composeAndInitialize());
initialize();
}
if (!jung) {
cho = code;
}
else {
jong = code;
}
}
else if (code >= 0x314f && code <= 0x3163) { // mo
if (!cho) {
array.push(char);
initialize();
continue;
}
if (jung && !jong) {
array.push(composeAndInitialize());
array.push(char);
continue;
}
if (jong) {
array.push(compose(ChoSeong.indexOf(cho), JungSeong.indexOf(jung), 0));
cho = jong;
jung = jong = 0;
}
jung = code;
}
else {
if (cho) {
if (jung) {
array.push(composeAndInitialize())
}
else {
array.push(String.fromCodePoint(cho));
initialize();
}
}
array.push(char);
}
}
if (cho) {
if (jung) {
array.push(composeAndInitialize())
}
else {
array.push(String.fromCodePoint(cho));
initialize();
}
}
return array.join('');
function composeAndInitialize() {
const result = compose(ChoSeong.indexOf(cho), JungSeong.indexOf(jung), jong && JongSeong.indexOf(jong));
initialize();
return result;
}
function initialize() {
cho = jung = jong = 0;
}
function compose(cho, jung, jong) {
return String.fromCodePoint(0xAC00 + 28 * 21 * cho + 28 * jung + jong);
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment