String obfuscation

I have the following problem, I need to convert a string of dotts and dashes to alphanumeric string using JavaScript, like so:

  1. Replace the number of consecutive dots with a number
  2. replace the number of consecutive dashes with the letter of the alphabet at that position

example: ... = 3, --.- = b1a, ..-. = 2a1

Given string ../.-|--/..|-./-|.-.|---|..-|-...|.-..|. should output -> 2/1A|B/2|A1/A|1A1|C|2A|A3|1A2|1.

All the | and / needs to stay at their position untouched.

Please help!

1 answer

  • answered 2020-11-20 11:29 Terry Lennox

    We can do something like below, iterating over each character using reduce, there should be a little scope to simplify the logic which I will work on!

    const input = '../.-|--/..|-./-|.-.|---|..-|-...|.-..|.';
    
    const { res } = Array.prototype.reduce.call(input, (acc, c, index, inp) => {
        if (c === '.') {
          acc.dots++;
        } else if (c === '-') { 
          acc.dashes++;
        } 
        
        if ((c !== '.' || index === inp.length-1) && acc.dots) { 
          acc.res += String(acc.dots);
          acc.dots = 0;
        }
        if ((c !== '-' || index === inp.length-1) && acc.dashes) { 
          acc.res += String.fromCharCode(64 + acc.dashes);
          acc.dashes = 0;
        }
        if (c === "/" || c === "|") { 
          acc.res += c;
        }
        return acc;
    }, { dots: 0, dashes: 0, res: "" });
    
    console.log("Result:", res)