-
Notifications
You must be signed in to change notification settings - Fork 269
Classics #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Classics #10
Changes from 4 commits
12f9ba2
c376de5
c801b3e
76b9ace
408dc13
479e925
20280c8
c2eec66
dbd3dbd
8a9d8b8
f04d86c
602df1f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/** | ||
* Most simplest encryption scheme. Read more: [http://practicalcryptography.com/ciphers/caesar-cipher/] | ||
* @param {String} str | ||
* @param {Number} num | ||
*/ | ||
|
||
function caeserCipher(str, num) { | ||
const lowerCaseString = str.toLowerCase(); | ||
const alphabets = 'abcdefghijklmnopqrstuvwxyz'.split(''); | ||
const totalAlphabets = alphabets.length; | ||
let result = ''; | ||
|
||
// handle large number, like 300 or -300 | ||
num %= totalAlphabets; | ||
|
||
for (let index in lowerCaseString) { | ||
// get the current character | ||
const currentCharacter = lowerCaseString[index]; | ||
|
||
// if character is space, add it to the result and continue to next | ||
if (currentCharacter === ' ') { | ||
result += currentCharacter; | ||
continue; | ||
} | ||
|
||
// determine the new index | ||
const currentIndex = alphabets.indexOf(currentCharacter); | ||
|
||
let newIndex = currentIndex + num; | ||
|
||
// if the index passes 25, restart from 0 | ||
if (newIndex > totalAlphabets - 1) { | ||
newIndex -= totalAlphabets; | ||
} | ||
|
||
if (newIndex < 0) { | ||
newIndex = totalAlphabets + newIndex; | ||
} | ||
|
||
// check if the character in original string was upper case | ||
if (str[index] === str[index].toUpperCase()) { | ||
result += alphabets[newIndex].toUpperCase(); | ||
} else { | ||
result += alphabets[newIndex]; | ||
} | ||
} | ||
return result; | ||
} |