function encrypt(text, n) {
let odd = [];
let even = [];
let punc = [];
for(let i = 0; i < n; i++) {
text.split('').forEach((el,i,arr) => {
if(el === '!'||el === '.'||el ==='?'){
punc.push(el);
} else if(i % 2 === 0) {
odd.push(el);
} else {
even.push(el);
}
})
text = even.concat(odd).concat(punc).join('');
}
return text;
}
console.log(encrypt("This is a test!", 1));
Hello, I am trying to encrypt string input by separating each characters, taking every second character and place those in the front, I will do that n times which is another parameter.
The trouble I am having now is the code above works well if the number we need to encrypt is 1,
"hsi etTi sats!"
but from 2, It did work oddly.
when I put an input like,
console.log(encrypt("This is a test!", 2));
I expected
"s eT ashi tist!"
but, for some reason, it is not like that, I think there is some problem in the statement where I reassign 'text' as the result of the loop. What I have thought was that if I reassign the result as 'text' that will go through the loop again, then I would have the result I want. but clearly, it was wrong.
Can you help me to understand why this reassigning does not work in a way I understood?
if(el === '!'|'.'|'?'){does not do what you think it doesif (el === '!' || el === '.' || el === '?'){insteadn?