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?
Consecutive pairwise character swapping of/within a string very easily can be solved by a reduce task ...
function swapCharsPairwise(value) {
return String(value)
.split('')
.reduce((result, antecedent, idx, arr) => {
if (idx % 2 === 0) {
// access the Adjacent (the Antecedent's next following char).
adjacent = arr[idx + 1];
// aggregate result while swapping `antecedent` and `adjacent`.
result.push(adjacent, antecedent);
}
return result;
}, []).join('');
}
console.log(
'swapCharsPairwise("astnbodei") ...',
swapCharsPairwise("astnbodei")
);
Did you try going through the array in pairs and swapping using ES6 syntax?
You can swap variables like this in ES6:
[a, b] = [b, a]
Below is one way to do it. The code you have is not valid because return is not allowed outside a function.
let string = "astnbodei";
let myArray = string.split('');
let outputArray = [];
for (i=0; i<myArray.length; i=i+2) {
outputArray.push(myArray[i+1]);
outputArray.push(myArray[i]);
}
console.log(outputArray.join(''));