如何在没有所有重复的情况下编写这段代码
// I have a loop which decrements m each time
// set m to the starting point
m = mid
// set f to a calculated array value
f = dict[l].substr( l * --m, l )
while (f.substr(0,x) === word && (!limit || matches.length < limit)){
matches.push(f);
// same as what was defined outside the while loop
// which seems to me like unnecessary repetition
f = dict[l].substr( l * --m, l )
}
// then I repeat it all, but incrementing m
// reset m to the starting point
m = mid
f = dict[l].substr( l * m++, l )
while (f.substr(0,x) === word && (!limit || matches.length < limit)){
matches.push(f);
f = dict[l].substr( l * m++, l )
}
有两个部分...
- 每个 block 包含一个重复的
f = ...
部分 - 重复 block ,仅更改
m
的增量/减量
编辑:代码的作用...
mid
表示按字母顺序排序的固定长度单词列表中的任意入口点,不带分隔符。我的目标是列出与一组前缀匹配的所有单词,因此必须找到任意mid
点(通过二分搜索方法输入)向后和向前的所有单词。
编辑:更多详细信息...
字典看起来像这样:
dict = [
"", // offset other values to equal word length
"ai", // all length 1
"inatonuptogo", // all length 2
"catcrydogendgodhamhathit", // all length 3
"foodhackhallhandhardhatehatshavehellridewood" // all length 4
]
l
是搜索单词的单词长度,因此 dict[l]
是字典中的一行单词,长度为 l
。
我正在修改John Resig's binary search method这样它将匹配一个前缀而不是整个单词,并返回一组结果,而不是一个真值。我还在那里设置了限制,因为我将使用它作为自动完成函数,该函数只需要几个返回值,而不是所有匹配。
最佳答案
您可以将循环放入函数中,因为除了递增/递减之外,它们是相同的:
function helperFunction(m, f, l, mid, dict, matches, limit, increment)
{
m = mid;
if (increment)
f = dict[l].substr(l * m++, l);
else f = dict[l].substr(l * --m, l);
while (f.substr(0, x) === word && (!limit || matches.length < limit))
{
matches.push(f);
f = dict[l].substr(l * m, l);
if (increment)
f = dict[l].substr(l * m++, l);
else f = dict[l].substr(l * --m, l);
}
}
我已将所有变量包含在参数列表中,因为它们的范围不清楚。
关于javascript - 删除重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11423096/