Skip to content

Instantly share code, notes, and snippets.

@karapetyan
Created April 13, 2018 00:02
Show Gist options
  • Select an option

  • Save karapetyan/3806ef91019cbfb8c8980d2c21ddcbdf to your computer and use it in GitHub Desktop.

Select an option

Save karapetyan/3806ef91019cbfb8c8980d2c21ddcbdf to your computer and use it in GitHub Desktop.
function encrypt(text, n) {
if ( !text || text.length <= 1) return text;
let result = text.split('');
for(let i = 0; i < n; i++) {
let odds = [];
for(let i = 0; i < result.length; i++) {
odds = odds.concat(result.splice(i, 1));
}
result = result.concat(odds);
}
return result.join("");
}
function decrypt(encryptedText, n) {
if ( !encryptedText || encryptedText.length <= 1) return encryptedText;
let encryptedArr = encryptedText.split('');
let firstPart = [];
let middle = countMiddle(encryptedArr);
console.log(middle);
let decrypted = [];
for (let i = 0; i < n; i++ ) {
firstPart = encryptedArr.splice(middle, encryptedArr.length - middle);
for (let i = 0; i < encryptedText.length; i++ ) {
isOdd(i) ?
decrypted = decrypted.concat(encryptedArr.splice(0, 1)):
decrypted = decrypted.concat(firstPart.splice(0, 1))
}
encryptedArr = decrypted;
decrypted = [];
}
return encryptedArr.join("");
}
function isOdd(num) {
return num % 2 !== 0;
}
function countMiddle(arr) {
return Math.floor(arr.length / 2 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment