Coding interview set 9


 

Let's begin with set 9,

18) Write a logic that takes input as  EC:B0:8T:E4 and response should be "0C:B0:80:04".
Wrong solution is already provided find the issue in that?

let mac = 'EC:B0:8T:E4'

const mapper = {
    E: 0,
    T: 0
}


Wrong solution:
var decoded="";
for(let item of mac){

    decoded=decoded+ mapper[item]!=undefined?mapper[item]:item;
}
console.log(decoded);


The issue with this solution:

+ vs. ?:
In JavaScript, the + operator has higher precedence than the ?: operator. This means that concatenation will take place before the condition in a ternary is evaluated. This can lead to some strange results.

 Note: operator associativity and precedence can change between languages. For example, in JavaScript the ?: operator is right-associative but it's left-associative in PHP. These same comparisons will produce different results between these languages.


One of the correct solutions with () as it has higher precedence :

var decoded="";

for(let item of mac){

    decoded=decoded+ (mapper[item]!=undefined?mapper[item]:item);

}

console.log(decoded);

Comments

Popular posts from this blog

Node JS:Understanding bin in package.json.

Node.js: create an excel file with multiple tabs.

Node.js: Downloading a xml file from given url and reading its data elements.