0

I am trying to decode my string using JavaScript. Here is my code on JSBin.

decordMessage('oppeeennnn','1234');

    function decordMessage(m,k) {
        var msg = m.split('');
        var keysplit = k.split('');
        var str ='';
        var j =0
        for (var i=0;i<msg.length;){
            str += msg[i];
            if(j < keysplit.length -2 &&i < keysplit.length && keysplit[j]){
                i = i + parseInt(keysplit[j]);
                j++;
            }

            console.log(i +"i")
            console.log(str);
        }
        console.log("after");
        console.log(str);
    }

I make a function in which message and key is passed.

Expected output :: open

Actually string charters are repeated in input message (encrypted message) using key. So I need to decode the message.

0

2 Answers 2

1

You forgot to put a break in the else condition, that's why it was looping infinitely till it ran out of memory. Run it in a browser and the tab will crash:

decordMessage('oppeeennnn','1234');

function decordMessage(m,k) {
    var msg = m.split('');
    var keysplit = k.split('');
    var str ='';
    var j =0
    for (var i=0;i<msg.length;){
        str += msg[i];
        if(j < keysplit.length &&i < keysplit.length && keysplit[j]){
            i = i + parseInt(keysplit[j]);
            j++;
        }
        else
          break;
    }
    console.log("after");
    console.log(str); // prints open
}

By the way, a better way to write the loop would be:

function decordMessage(m,k) {
    var msg = m.split('');
    var keysplit = k.split('');
    var str = '';
    var j = 0, i = 0;
    while (j < keysplit.length 
        && i < msg.length) {
        str += msg[i]; 
        i += parseInt(keysplit[j]);
        j++;
    }
    console.log(str)
}
Sign up to request clarification or add additional context in comments.

Comments

1

This may helps you.

decordMessage('oppeeennnn', '1234');

function decordMessage(m, k) {

  var arr = m.split("");

  uniqueArray = arr.filter(function(item, pos) {
    return arr.indexOf(item) == pos;
  });

  console.log(uniqueArray.join(""));
}

Assuming encryption logic goes as 123456....

Sample here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.