All files / exercises/rotational-cipher index.ts

100% Statements 23/23
81.81% Branches 9/11
100% Functions 3/3
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 10725x                                                       1x                                                           1x   40x 40x     40x   27x 27x   27x 21x     6x       13x   5x 5x       8x     2x                   2x 2x   2x 40x     2x    
const letters = [
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z",
];
const index: { [key: string]: number } = {
  a: 0,
  b: 1,
  c: 2,
  d: 3,
  e: 4,
  f: 5,
  g: 6,
  h: 7,
  i: 8,
  j: 9,
  k: 10,
  l: 11,
  m: 12,
  n: 13,
  o: 14,
  p: 15,
  q: 16,
  r: 17,
  s: 18,
  t: 19,
  u: 20,
  v: 21,
  w: 22,
  x: 23,
  y: 24,
  z: 25,
};
 
// Add any helper functions you may need here
function encrypt(char: string, rotationFactor: number): string {
  // to make sure all upper and lower case letters are taken into account
  const lowerCaseChar = char.toLowerCase();
  const entry = index[lowerCaseChar];
 
  // it is a letter because an entry has been found in the index
  if (entry !== undefined) {
    // shift the index module 26 (the size of the alphabet)
    const shiftedIndex = (Number(entry) + rotationFactor) % 26;
    const encryptedLetter = letters[shiftedIndex];
    // the original character was already lower case
    if (char === lowerCaseChar) {
      return encryptedLetter;
    }
    // the original character was upper case
    return encryptedLetter.toUpperCase();
  }
 
  // if it is an integer number
  if (!isNaN(Number(char))) {
    // shift the index module 10 (the size of the numeric list)
    const shiftedIndex = (Number(char) + rotationFactor) % 10;
    return `${shiftedIndex}`;
  }
 
  // It is a symbol, keep it unchanged
  return char;
}
 
export function rotationalCipher(
  input: string,
  rotationFactor: number,
): string {
  /**
   * We can resize the "rotationFactor" by using the modular arithmetic
   * The module is the size of the input and rotationFactor % input.length
   * gives the new rotation factor bound to the size (and reduce the constant part of the runtime complexity)
   */
 
  const inputArray = Array.from(input);
  const responseArray = new Array(inputArray.length);
 
  for (let i = 0; i < inputArray.length; i += 1) {
    responseArray[i] = encrypt(inputArray[i], rotationFactor);
  }
 
  return responseArray.join("");
}