JSFiddle - React, Tailwind, and code Playground
by brigand
HTML
<h3>Rot13 converter</h3>
<textarea rows="4" cols="50" id="text"></textarea>
<p><button type="button" onclick="convert()">Convert</button></p>
JavaScript
function convert() {
let textarea = document.getElementById("text");
textarea.value = rot13(textarea.value)
}
function rot13(text) {
const points = [...text].map(char => char.codePointAt(0));
const rotated = points
.map(rot13Point)
.map(point => String.fromCodePoint(point))
.join('');
return rotated;
}
const A_LOWER = 'a'.codePointAt(0);
const A_UPPER = 'A'.codePointAt(0);
const Z_LOWER = 'z'.codePointAt(0);
const Z_UPPER = 'Z'.codePointAt(0);
const LETTERS = 26;
function rot13Point(point) {
const lower = point - A_LOWER;
const upper = point - A_UPPER;
if (lower >= 0 && lower < LETTERS) {
return A_LOWER + add13Wrapping(lower);
} else if (upper >= 0 && upper < LETTERS) {
return A_UPPER + add13Wrapping(upper);
} else {
return point;
}
}
function add13Wrapping(number) {
return (number + LETTERS / 2) % LETTERS;
}