简体   繁体   中英

Simplify the design for auto-suggestion

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);
};

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?
 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM