Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement