0

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?

SH Kim
  • 99
  • 6

1 Answers1

1

You needed to reset your 3 arrays back to an empty array on each iteration of n.

...
text = even.concat(odd).concat(punc).join('');
odd = [];
even = [];
punc = [];
....

Also, your if statement was wrong:

if(el === '!'|'.'|'?')

should be

if(el === '!'|| el === '.' || el === '?')

Working example below:

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('');
        odd = [];
        even = [];
        punc = [];
    }
    return text;
}

console.log(encrypt("This is a test!", 1));
console.log(encrypt("This is a test!", 2));
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Ohhh now I got the problem. Thanks so much for your comment! Your first comment is so much understandable right away – SH Kim Dec 06 '19 at 10:45