How would I write this code without all the duplication
// 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 )
}
There are two parts…
- each block contains a repeating
f = ...part - the blocks are repeated, only changing the increment/decrement of
m
EDIT: What the code does…
mid represents an arbitrary entry point into an alphabetically sorted list of fixed length words with no separators. I am aiming to list all the words that match a set prefix, so must find all the words backwards of the arbitrary mid point (as entered by binary search method) and also forwards.
Edit: Further details…
dictionary looks like this:
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 is word length of searched words, so dict[l] is one row of words from the dictionary, of length l.
I am modifying John Resig’s binary search method so that it will match a prefix rather than a whole word, and return a set of results, rather than a truthy value. I am also putting a limit in there, as I will be using this for an autocomplete function which only requires a few returned values, not all matches.
You might pull the loops into a function, since aside from the increment/decrement, they are identical:
I’ve included all the variables in the argument list since their scope is unclear.