|
| 1 | +function getPosUp(pos) { |
| 2 | + if (pos === alphabet.length - 1) { |
| 3 | + return 0; |
| 4 | + } else { |
| 5 | + return pos + 1; |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +function getPosDown(pos) { |
| 10 | + if (pos === 0) { |
| 11 | + return alphabet.length - 1; |
| 12 | + } else { |
| 13 | + return pos - 1; |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +function getNextChar(currChar, direction) { |
| 18 | + var pos = alphabetMap[currChar]; |
| 19 | + var nextPos = direction === 'up' ? getPosUp(pos) : getPosDown(pos); |
| 20 | + var nextChar = alphabet.charAt(nextPos); |
| 21 | + logger._print(currChar + ' -> ' + nextChar); |
| 22 | + return nextChar; |
| 23 | +} |
| 24 | + |
| 25 | +function cipher(str, rotation, direction, cipherTracer) { |
| 26 | + if (!str) return ''; |
| 27 | + |
| 28 | + for (var i = 0; i < str.length; i++) { |
| 29 | + |
| 30 | + var currChar = str.charAt(i); |
| 31 | + var r = rotation; |
| 32 | + |
| 33 | + logger._print('Rotating ' + currChar + ' ' + direction + ' ' + rotation + ' times'); |
| 34 | + cipherTracer._notify(i)._wait(); |
| 35 | + |
| 36 | + // perform given amount of rotations in the given direction |
| 37 | + while (--r > 0) { |
| 38 | + currChar = getNextChar(currChar, direction); |
| 39 | + cipherTracer._notify(i, currChar)._wait(); |
| 40 | + } |
| 41 | + |
| 42 | + logger._print('Rotation result: ' + currChar); |
| 43 | + |
| 44 | + str = str.substring(0, i) + currChar + str.substring(i + 1); |
| 45 | + |
| 46 | + logger._print('Current result: ' + str); |
| 47 | + } |
| 48 | + |
| 49 | + cipherTracer._select(0, i); |
| 50 | + return str; |
| 51 | +} |
| 52 | + |
| 53 | +function encrypt(str, rotation) { |
| 54 | + logger._print('Encrypting: ' + str); |
| 55 | + return cipher(str, rotation, 'down', encryptTracer); |
| 56 | +} |
| 57 | + |
| 58 | +function decrypt(str, rotation) { |
| 59 | + logger._print('Decrypting: ' + str); |
| 60 | + return cipher(str, rotation, 'up', decryptTracer); |
| 61 | +} |
| 62 | + |
| 63 | +var encrypted = encrypt(string, rotation); |
| 64 | +logger._print('Encrypted result: ' + encrypted); |
| 65 | + |
| 66 | +decryptTracer._setData(encrypted); |
| 67 | +var decrypted = decrypt(encrypted, rotation); |
| 68 | +logger._print('Decrypted result: ' + decrypted); |
0 commit comments