0

I'm trying to implement a function which checks whether a list of letters are all present in a word.

function wordHasLatters(word,letters){
    let wordChars={};
    word.split("").map(c=>wordChars[c]=true);
    let ok=true;
    letters.split("").map(l=>ok=ok&&(wordChars[l]!=undefined));
    return ok;
}

It is all relatively elegant with using maps. What bothers me is that I cannot return from the second map if I detect that a letter is not present. So I have to use a variable and return this. This is two extra lines in the code.

Is there a way to optimize this code?

sbtpr
  • 541
  • 5
  • 18
  • A break won't return from the containing block. I would still have to maintain a variable and return that. – sbtpr Dec 28 '17 at 21:58
  • It would be helpful if you'd read more than the title... – jonrsharpe Dec 28 '17 at 21:58
  • 2
    What is this trend with people using `.map()` and ignoring its result. This is either a case for `.reduce()` or for imperative loops. Using `.map()` is just so odd here. –  Dec 28 '17 at 22:01
  • 1
    Indeed, both uses of `.map()` are incorrect. `.map()` should only be used to convert one array to another array of the same length, by returning an array element value in each iteration, and then assigning the result of `.map()` to a variable. – Michael Geary Dec 28 '17 at 22:10

1 Answers1

2
 const wordHasLetters = (word,letters) => letters.every(letter => word.includes(letter));

or use a plain old for loop:

 function wordHasLetters(word, letters){
   const hash = {};
   for(var char of word)
     hash[char] = true;
   for(var letter of letters)
     if(!hash[letter]) return false;
   return true;
 }

Or using a Set:

 function wordHasLetters(word, letters){
   const set = new Set(letters);
   for(var char of word){
     set.delete(char);
     if(!set.size) return true;
   }
   return false;
 }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151