Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Everybody hates typing text and since you've already adopted the lazy mindset of a programmer,
- it's time you made your life easier! Your task is to write a JavaScript program that takes a text of words
- (space-separated) and a given keyword, and then autocompletes that keyword with a suitable match
- from the provided text. The matched word should follow the rules:
- It should contain the keyword from start – e.g. "wolf" matches "wo", but not "olf".
- If there are multiple matches, the shortest word should be returned. If two words are equally long,
- the lexicographically lesser word should be returned.
- Word match should be case insensitive. */
- "use strict";
- function autoCompleteWord(args) {
- var words = args[0].split(/\s+/g).filter(Boolean);
- for (var i = 1; i < args.length; i += 1) {
- var keyword = args[i].toLowerCase();
- var foundWords = [];
- for (var j = 0; j < words.length; j += 1) {
- var currentWord = words[j];
- if (currentWord.toLowerCase().indexOf(keyword) == 0) {
- foundWords.push(currentWord);
- }
- }
- if (foundWords.length == 0) {
- foundWords.push('-');
- }
- foundWords.sort(function(a, b) {
- if (a.length != b.length) {
- return a.length - b.length;
- }
- return a.localeCompare(b);
- });
- console.log(foundWords[0]);
- }
- }
- autoCompleteWord([
- 'word screammm screech speech wolf',
- 'bas',
- 'wo',
- 'scr',
- 's'
- ]);
- autoCompleteWord([
- 'firefox mozilla gecko webKit lord battery skype',
- 'firf',
- 'fire',
- 'momo',
- 'skyp',
- 'lord',
- 'webk'
- ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement