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?

4
  • A break won't return from the containing block. I would still have to maintain a variable and return that. Commented Dec 28, 2017 at 21:58
  • It would be helpful if you'd read more than the title... Commented Dec 28, 2017 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. Commented Dec 28, 2017 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. Commented Dec 28, 2017 at 22:10

1 Answer 1

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

The first one is just wonderful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.