Last active
January 22, 2019 23:57
-
-
Save friendlyanon/fe92da2ae21313a642126e08458ff232 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isLetter(codePoint) { | |
if (65 <= codePoint && codePoint <= 90) return true; | |
if (97 <= codePoint && codePoint < 123) return true; | |
// maybe more cases for unicode | |
return false; | |
} | |
function reverseOnlyLetters(string) { | |
if (typeof string !== "string") return; | |
const length = string.length; | |
const array = length < 50 ? [] : Array(length); | |
for (let i = 0, k = 0; ; ++i, ++k) { | |
const c = string.codePointAt(i); | |
array[k] = c; | |
if (c > 0xFFFF) ++i; | |
if (i >= length) { | |
if (array.length !== k) array.length = k; | |
break; | |
} | |
} | |
for (let start = 0, end = array.length - 1; ; ++start, --end) { | |
while (!isLetter(array[start])) ++start; | |
while (!isLetter(array[end])) --end; | |
if (start >= end) break; | |
const temp = array[start]; | |
array[start] = array[end]; | |
array[end] = temp; | |
} | |
return String.fromCodePoint(...array); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment