简化设计的设计

发布于 2025-02-10 12:16:56 字数 845 浏览 3 评论 0原文

我的代码中有一个相当复杂的结构,它是在匹配的搜索中。 该建筑负责自动探索。 例如:有几个男性名字(亚当,阿德里安,阿诺德,迈克)。用户进入首字母“ A”并看到自动烟 - 亚当,阿德里安,阿诺德。然后,他进入字母“ D”,并留在自动烟中 - 亚当,阿德里安。等等。

是否可以以某种方式简化代码的这一部分?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

揪着可爱 2025-02-17 12:16:56

您可以获取输入字符串的长度,并将其用作切片的索引。更好的是,您可以使用startswith,并且如果需要将上或下情况归一化,例如

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

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?
 );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文