Advertisement
Guest User

Untitled

a guest
Aug 26th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. function dictionaryToWords(text) {
  2. if (text === '') return { };
  3. var map = { };
  4. var words = text.split(' ').filter(function(word) { return word !== ""; }); // [ I, *will*, fight, to, follow, I, will, fight, for, *love* ]
  5.  
  6. for (var i = 0; i < words.length; i++) {
  7. var currentWord = words[i];
  8.  
  9. // map["love"] === undefined
  10.  
  11. // the first case: currentWord is a new word => it is not in the map
  12. if (!map[currentWord]) {
  13. if ((i + 1) < words.length) {
  14. map[currentWord] = [ words[i + 1] ];
  15. }
  16. else {
  17. map[currentWord] = [];
  18. }
  19.  
  20. /*map[currentWord] = ((i + 1) < words.length
  21. ? [ words[i + 1] ]
  22. : []
  23. );*/
  24. }
  25. else {
  26. // the second case: currentWord is an existing word => it is in the map
  27. var followingWords = map[currentWord]; // fight: ['for']
  28.  
  29. // there is a next word after currentWord
  30. if ((i + 1) < words.length) {
  31. var nextWord = words[i + 1];
  32.  
  33. if (!followingWords.some(value => value === nextWord)) {
  34. followingWords.push(nextWord); // fight: ['for', 'to']
  35. }
  36. }
  37. }
  38. }
  39.  
  40. return map;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement