简化设计的设计
我的代码中有一个相当复杂的结构,它是在匹配的搜索中。 该建筑负责自动探索。 例如:有几个男性名字(亚当,阿德里安,阿诺德,迈克)。用户进入首字母“ 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以获取输入字符串的长度,并将其用作切片的索引。更好的是,您可以使用
startswith
,并且如果需要将上或下情况归一化,例如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