JSFiddle - React, Tailwind, and code Playground

by aninaslyan

HTML

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<table class="noborder">
		<tbody>
			<tr>
				<td><label for="text">Text:</label></td>
				<td><textarea id="text" cols="50" rows="10" style="width:40em; height:15em">NASA or the National Aeronautics and Space Administration is the part of the United States government that deals with space exploration and aeronautics, the operating and designing of planes.</textarea></td>
			</tr>
			<tr>
				<td><label for="text">Encrypted Text:</label></td>
				<td><textarea id="text2" cols="50" rows="10" style="width:40em; height:15em"></textarea></td>
			</tr>
			<tr>
				<td><label for="key">Key:</label></td>
				<td><input type="text" id="key" style="width:10em;"/></td>
			</tr>
			<tr>
				<td></td>
				<td>
					<input type="button" value="Encrypt" onclick="doCrypt()"/>
				</td>
			</tr>
		</tbody>
	</table>
</body>
<script type="text/javascript" src="script.js"></script>
</html>

JavaScript

function doCrypt(isDecrypt) {
  if (document.getElementById("key").value.length == 0) {
    alert("Key is empty");
    return;
  }
  let key = filterKey(document.getElementById("key").value);
  if (key.length == 0) {
    alert("Key has no letters");
    return;
  }
  if (isDecrypt) {
    for (let i = 0; i < key.length; i++)
      key[i] = (26 - key[i]) % 26;
  }
  let textElem = document.getElementById("text");
  let encryptedTextElem = document.getElementById("text2");

  encryptedTextElem.value = crypt(textElem.value, key);
}

function crypt(input, key) {
  let output = "";
  for (let i = 0, j = 0; i < input.length; i++) {
    let c = input.charCodeAt(i);
    if (isUppercase(c)) {
      output += String.fromCharCode((c - 65 + key[j % key.length]) % 26 + 65);
      j++;
    } else if (isLowercase(c)) {
      output += String.fromCharCode((c - 97 + key[j % key.length]) % 26 + 97);
      j++;
    } else {
      output += input.charAt(i);
    }
  }
  return output;
}

function filterKey(key) {
  let result = [];
  for (let i = 0; i < key.length; i++) {
    let c = key.charCodeAt(i);
    if (isLetter(c))
      result.push((c - 65) % 32);
  }
  return result;
}

function isLetter(c) {
  return isUppercase(c) || isLowercase(c);
}

function isUppercase(c) {
  return 65 <= c && c <= 90;
}

function isLowercase(c) {
  return 97 <= c && c <= 122;
}