Home > Blockchain >  Simplify the design for auto-suggestion
Simplify the design for auto-suggestion

Time:06-24

There is a rather complicated construction in my code, it is in const matchedSuggestions. This construction is responsible for auto-suggestions. For example: there are several male names (Adam, Adrian, Arnold, Mike). The user enters the first letter "A" and sees auto-suggestions - Adam, Adrian, Arnold. Then he enters the letter "D" and remains in auto-suggestions - Adam, Adrian. And so on.

Is it possible to somehow simplify this part of the code?

const onChange = (e) => {
  const { value } = e.target;
  setInput(value)

  if(value.length < 1) { setSuggestedTags([]); setIsValid([]);return; }
  
  const matchedSuggestions = tagSuggestions.filter((s) => {
    return s.slice(0, 2).search(value.slice(0, 2)) > -1 
        && s.slice(0, 1).search(value.slice(0, 1)) > -1
        && s.slice(0, 3).search(value.slice(0, 3)) > -1
        && !tags.includes(s)
  })
  setSuggestedTags(matchedSuggestions); 

  if (e.target.value) {
    setIsValid(() => /^[1-5][0-9]?[0-9]?$|^100$/.test(e.target.value));
  } else {
    setIsValid(true);
  }
  setInput(value);
};

CodePudding user response:

You could get the length of the input string and use it as index for slicing. Even better, you could use startsWith and if wanted normalized to upper or lower case, like

 value = value.toLowerCase();             // normalize
 tagSuggestions.filter(s =>
     s.toLowerCase().startsWith(value) && // or includes(value) in case you want to validate part of the string
     !tags.includes(s)                    // what is this for?
 );
  • Related