Search code examples
javascriptarraysstringalgorithmswap

Swapping consecutive/adjacent characters of a string in JavaScript


Example string: astnbodei, the actual string must be santobedi. Here, my system starts reading a pair of two characters from the left side of a string, LSB first and then the MSB of the character pair. Therefore, santobedi is received as astnbodei. The strings can be a combination of letters and numbers and even/odd lengths of characters.

My attempt so far:

var attributes_ = [Name, Code,
    Firmware, Serial_Number, Label
]; //the elements of 'attributes' are the strings
var attributes = [];

for (var i = 0; i < attributes_.length; i++) {
    attributes.push(swap(attributes_[i].replace(/\0/g, '').split('')));
}

function swap(array_attributes) {
    var tmpArr = array_attributes;
    for (var k = 0; k < tmpArr.length; k += 2) {
        do {
            var tmp = tmpArr[k];
            tmpArr[k] = tmpArr[k+1]
            tmpArr[k+1] = tmp;
        } while (tmpArr[k + 2] != null);
    }
    return tmpArr;
}

msg.Name = attributes; //its to check the code

return {msg: msg, metadata: metadata,msgType: msgType}; //its the part of system code

While running above code snippet, I received the following error:

Can't compile script: javax.script.ScriptException: :36:14 Expected : but found ( return {__if(); ^ in at line number 36 at column number 14

I'm not sure what the error says. Is my approach correct? Is there a direct way to do it?


Solution

  • The reason for the error in the question was the placement of the function swap. However, switching its placement gave me another error:

    java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: javax.script.ScriptException: delight.nashornsandbox.exceptions.ScriptCPUAbuseException: Script used more than the allowed [8000 ms] of CPU time.

    @dikuw's answer helped me partially. The following line of code worked for me:

    var attributes_ = [Name, Code,
        Firmware, Serial_Number, Label
    ]; //the elements of 'attributes' are the strings
    var attributes = [];
    
    for (var i = 0; i < attributes_.length; i++) {
        attributes.push(swap(attributes_[i].replace(/\0/g, '').split('')));
    }
    
    return {msg: msg, metadata: metadata,msgType: msgType};
    
    function swap(array_attributes) {
        var tmpArr = [];
        for (var k = 0; k < array_attributes.length; k= k+2) {
            if( (array_attributes[k + 1] != null)) {
                tmpArr.push(array_attributes[k+1]);
                tmpArr.push(array_attributes[k]);
        }}
        return tmpArr.join('');
    }