CatTail
6/10/2016 - 2:20 AM

Barcode name popular in StarCraft

Barcode name popular in StarCraft

'use strict'

const MAP = {
  'A': '.-',
  'B': '-...',
  'C': '-.-.',
  'D': '-..',
  'E': '.',
  'F': '..-.',
  'G': '--.',
  'H': '....',
  'I': '..',
  'J': '.---',
  'K': '-.-',
  'L': '.-..',
  'M': '--',
  'N': '-.',
  'O': '---',
  'P': '.--.',
  'Q': '--.-',
  'R': '.-.',
  'S': '...',
  'T': '-',
  'U': '..-',
  'V': '...-',
  'W': '.--',
  'X': '-..-',
  'Y': '-.--',
  'Z': '--..',
  'Á': '.--.-', // A with acute accent
  'Ä': '.-.-',  // A with diaeresis
  'É': '..-..', // E with acute accent
  'Ñ': '--.--', // N with tilde
  'Ö': '---.',  // O with diaeresis
  'Ü': '..--',  // U with diaeresis
  '1': '.----',
  '2': '..---',
  '3': '...--',
  '4': '....-',
  '5': '.....',
  '6': '-....',
  '7': '--...',
  '8': '---..',
  '9': '----.',
  '0': '-----',
  ',': '--..--',  // comma
  '.': '.-.-.-',  // period
  '?': '..--..',  // question mark
  ';': '-.-.-',   // semicolon
  ':': '---...',  // colon
  '/': '-..-.',   // slash
  '-': '-....-',  // dash
  "'": '.----.',  // apostrophe
  '()': '-.--.-', // parenthesis
  '_': '..--.-',  // underline
  '@': '.--.-.',  // at symbol from http://www.learnmorsecode.com/
  ' ': '.......',
}

const CHR_ENCODE_MAP = Object.keys(MAP)
    .reduce((map, chr) => {
        map[chr] = MAP[chr].replace(/\./g, 'I').replace(/-/g, 'l')
        return map
    }, {})

const ENCODE_CHR_MAP = Object.keys(CHR_ENCODE_MAP)
    .reduce((map, chr) => {
        map[CHR_ENCODE_MAP[chr]] = chr
        return map
    }, {})

function encode(str) {
    return str.split('')
        .map((chr) => CHR_ENCODE_MAP[chr.toUpperCase()])
        .join('')
}

function decode(encodeStr) {
    if (!encodeStr) {
        return ['']
    }

    let values = []
    for (let encodeChr in ENCODE_CHR_MAP) {
        if (encodeStr.indexOf(encodeChr) === 0) {
            let subValues = decode(encodeStr.slice(encodeChr.length))
            .map((value) => ENCODE_CHR_MAP[encodeChr] + value)
            values = values.concat(subValues)
        }
    }
    return values
}

console.log(decode(encode('CatTail')))

console.log(encode('CatTail')) // lIlIIlllIlIIIlII