Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real Time Morse code converter in Javascript

After seeing Google's april fools joke of the morse code gmail, I thought I'd try to create a real-time morse code converter in javascript.

I'm using regex and replace to change the morse code into character. For example:

.replace(/.- /g, "a").replace(/.-. /g, "r")

The issue I'm having is that when I'm typing .-. for "r" it give me an "a" because it sees .- first. How can I make it replace only exact matches?

Updated and working!! Thanks to every one that helped me

http://jsfiddle.net/EnigmaMaster/sPDHL/32/ - My Original code

http://jsfiddle.net/EnigmaMaster/LDKKE/6/ - Rewritten by Shawn Chin

http://jsfiddle.net/EnigmaMaster/y9A4Y/2/ - Rewritten by Matthias Tylkowski

If anyone has other ways of writting this program please post a JsFiddle

Id love to see how else this can be done

like image 981
EnigmaMaster Avatar asked Apr 18 '12 16:04

EnigmaMaster


3 Answers

Your question highlights an interesting fact: the Morse code is not a prefix code. So you need some kind of separator—spaces, commas, etc.—to delimit code symbols.

You seem to have decided to use spaces, that's fine.

This being said, what's missing in your regex is the escaping of the dot symbols (use /\.- / instead of /.- /)

like image 114
lum Avatar answered Oct 19 '22 21:10

lum


Another way of doing it is using a dichotomic search.

enter image description here

A graphical representation of the dichotomic search table: the user branches left at every dot and right at every dash until the character is finished.

like image 3
Vitim.us Avatar answered Oct 19 '22 22:10

Vitim.us


The other answers have already covered the reasons why your example was not working so I'll refrain from repeating them.

However, may I suggest that since you're already using spaces to delimit each code, a straight-forward solution would be to do a simple .split() to segment the input text into individual units then simply do a one-to-one mapping of code to chars. This will be a lot more efficient than repeated regex replacements and less prone to errors.

For example:

var morse = {  // use object as a map
    '.-': 'a', 
    '-...': 'b', 
    '-.-.': 'c', 
    // .... the rest ...
};

function translate_morse(code) {  // given code, return matching char
    return (typeof morse[code] === "undefined") ? "" : morse[code];
    // if the var is not found, the code is unknown/invalid. Here we 
    // simply ignore it but you could print out the code verbatim and use
    // different font styles to indicate an erroneous code
}

// example usage
translated = code_text.split(" ").map(translate_morse).join("");

Here's a working example: http://jsfiddle.net/KGVAm/1/

p.s. I've taken the liberty of tweaking the code and the behaviour a little, i.e. disabling the input of other chars but allowing backscape to allow corrections.

like image 1
Shawn Chin Avatar answered Oct 19 '22 22:10

Shawn Chin