Skip to content

Instantly share code, notes, and snippets.

@hejrobin
Created September 1, 2011 11:28
Show Gist options
  • Save hejrobin/1185988 to your computer and use it in GitHub Desktop.
Save hejrobin/1185988 to your computer and use it in GitHub Desktop.
Awesome Javascript Lexer-thingy
(function() {
var Lingo = this.Lingo = {};
Lingo.Dictionary = function(dictionary) {
this.setDictionary(dictionary);
};
Lingo.Dictionary.prototype = {
setDictionary: function(dictionary) {
this.dictionary = dictionary;
},
getDictionary: function() {
return this.dictionary;
},
translateWord: function(word, dict) {
var lang = (dict !== undefined) ? dict : this.dictionary.lexicon;
var translated = [];
if(word in lang.words) {
return lang.words[word];
} else {
var char_list = lang.characters;
var chars = word.split('');
for(var n = 0; n < chars.length; ++n) {
var char = chars[n];
if(char in char_list)
translated.push(char_list[char]);
else
translated.push(char);
}
}
if(translated.length > 0)
return translated.join('');
return word;
},
defineWord: function(word) {
var lang = this.dictionary.lexicon;
var dict = {};
var tmp = {};
for(var key in lang.words) {
tmp[lang.words[key]] = key;
dict.words = tmp;
}
tmp = {};
for(var key in lang.characters) {
tmp[lang.characters[key]] = key;
dict.characters = tmp;
}
lang = dict;
if(word in lang.words) {
return lang.words[word];
} else {
var char_list = lang.characters;
for(var char in char_list) {
var chr = char_list[char];
word = word.replace(new RegExp(char, 'g'), chr);
}
}
return word;
},
translate: function(string) {
var translated = [];
var words = string.split(' ');
for(var n = 0; n < words.length; ++n)
translated.push(this.translateWord(words[n]));
return translated.join(' ');
},
define: function(string) {
var translated = [];
var words = string.split(' ');
for(var n = 0; n < words.length; ++n)
translated.push(this.defineWord(words[n]));
return translated.join(' ');
}
};
Lingo.Lexer = function() {
this.lexicons = {};
};
Lingo.Lexer.prototype = {
setLexicon: function(id, lexicon) {
if(lexicon instanceof Lingo.Dictionary)
this.lexicons[id] = lexicon;
},
getLexicon: function(id) {
return this.lexicons[id];
},
translate: function(string, lexicon_id) {
return this.getLexicon(lexicon_id).translate(string);
},
define: function(string, lexicon_id) {
return this.getLexicon(lexicon_id).define(string);
}
};
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment