user5711656
user5711656

Reputation: 3678

how to decode string in javascript?

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.

Upvotes: 0

Views: 97

Answers (2)

forumulator
forumulator

Reputation: 875

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)
}

Upvotes: 1

mpsbhat
mpsbhat

Reputation: 2773

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

Upvotes: 1

Related Questions