Skip to content

Instantly share code, notes, and snippets.

@szabototo89
Created August 25, 2016 20:59
Show Gist options
  • Save szabototo89/01fe2054936688de72bc56af20ea39cf to your computer and use it in GitHub Desktop.
Save szabototo89/01fe2054936688de72bc56af20ea39cf to your computer and use it in GitHub Desktop.
function dictionaryToWords(text) {
if (text === '') return { };
var map = { };
var words = text.split(' ').filter(function(word) { return word !== ""; }); // [ I, *will*, fight, to, follow, I, will, fight, for, *love* ]
for (var i = 0; i < words.length; i++) {
var currentWord = words[i];
// map["love"] === undefined
// the first case: currentWord is a new word => it is not in the map
if (!map[currentWord]) {
if ((i + 1) < words.length) {
map[currentWord] = [ words[i + 1] ];
}
else {
map[currentWord] = [];
}
/*map[currentWord] = ((i + 1) < words.length
? [ words[i + 1] ]
: []
);*/
}
else {
// the second case: currentWord is an existing word => it is in the map
var followingWords = map[currentWord]; // fight: ['for']
// there is a next word after currentWord
if ((i + 1) < words.length) {
var nextWord = words[i + 1];
if (!followingWords.some(value => value === nextWord)) {
followingWords.push(nextWord); // fight: ['for', 'to']
}
}
}
}
return map;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment