Advertisement
dimipan80

Lab - AutoComplete

Nov 15th, 2014
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Everybody hates typing text and since you've already adopted the lazy mindset of a programmer,
  2.  it's time you made your life easier! Your task is to write a JavaScript program that takes a text of words
  3.  (space-separated) and a given keyword, and then autocompletes that keyword with a suitable match
  4.  from the provided text. The matched word should follow the rules:
  5.  It should contain the keyword from start – e.g. "wolf" matches "wo", but not "olf".
  6.  If there are multiple matches, the shortest word should be returned. If two words are equally long,
  7.  the lexicographically lesser word should be returned.
  8.  Word match should be case insensitive. */
  9.  
  10. "use strict";
  11.  
  12. function autoCompleteWord(args) {
  13.     var words = args[0].split(/\s+/g).filter(Boolean);
  14.  
  15.     for (var i = 1; i < args.length; i += 1) {
  16.         var keyword = args[i].toLowerCase();
  17.         var foundWords = [];
  18.         for (var j = 0; j < words.length; j += 1) {
  19.             var currentWord = words[j];
  20.             if (currentWord.toLowerCase().indexOf(keyword) == 0) {
  21.                 foundWords.push(currentWord);
  22.             }
  23.         }
  24.  
  25.         if (foundWords.length == 0) {
  26.             foundWords.push('-');
  27.         }
  28.  
  29.         foundWords.sort(function(a, b) {
  30.             if (a.length != b.length) {
  31.                 return a.length - b.length;
  32.             }
  33.             return a.localeCompare(b);
  34.         });
  35.  
  36.         console.log(foundWords[0]);
  37.     }
  38. }
  39.  
  40. autoCompleteWord([
  41.     'word screammm screech speech wolf',
  42.     'bas',
  43.     'wo',
  44.     'scr',
  45.     's'        
  46. ]);
  47.  
  48. autoCompleteWord([
  49.     'firefox mozilla gecko webKit lord battery skype',
  50.     'firf',
  51.     'fire',
  52.     'momo',
  53.     'skyp',
  54.     'lord',
  55.     'webk'
  56. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement