Convert HTML properties

Hello, so I passed the test using switch statements, but I am curious to know. What would be an efficient way to solve this same problem if lets say there is more special characters and writing switch statements just becomes to lengthy? Would if statements be better? My curiosity is getting the better of me here. I’m interested because those switch statements or if statements could very will take the program longer to check each statement.

Summary
function convertHTML(str) {
    return str.replace(/[&<>"']/g, function(character) {
        switch (character) {
            case '&':
                return '&amp;'
            case '<':
                return '&lt;'
            case '>':
                return '&gt;'
            case '"':
                return '&quot;'
            case "'":
                return '&apos;'
            default:
                return character;
        }
    });
}

console.log(convertHTML("Dolce & Gabbana"));

In a case like this where every branch of the switch statement is simply returning a value, then it could be rewritten with a look-up table using a plain Object or Map.

Object
const lookup = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&apos;',
};
return lookup[character] ?? character;
Map
const lookup = new Map([
  ['&', '&amp;'],
  ['<', '&lt;'],
  ['>', '&gt;'],
  ['"', '&quot;'],
  ["'", '&apos;'],
]);
return lookup.get(character) ?? character;

As far as performance goes it’s something you’d need to test for yourself, but I imagine that you’d need several more magnitudes of branches before the difference is noticeable (just guessing).

1 Like

Thank you for the explanation. I like your use of objects and maps really looks clean and concise. Bravo sir!!!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.