/**
* @param {string} str1 - the first string to compare
* @param {string} str2 - the second string to compare
* @returns {number} the absolute difference in length between `str1` and `str2`
*/
const getDistanceByLength = (str1, str2) => {
return Math.abs(str1.length-str2.length);
};
/**
* @param {string} word - the original string
* @param {string[]} words - an array of strings
* @param {(str1: string, str2: string) => number} - a function that
* takes two strings and returns a number representing the distance between them
* @param {number} threshold - the maximum distance that is still considered "close"
* @returns {string} the string in `words` with the minimum distance to `word`
* as calculated by `distanceFn`, unless that distance is strictly greater than
* the `threshold`, in which case the original `word` is returned.
*/
const getClosestWord = (word, words, getDistanceByLength, threshold) => {
for(i=0;i<words.length;i++){
if(getDistanceByLength(word,words[i]) <= threshold){
return words[i];
}
}
return word;
};
我遇到的问题是我无法弄清楚getClosestWord()
循环数组并得出最短距离(从getDistanceByLength
)所需的逻辑。word
如果距离大于 a ,它还会返回第一个threshold
。现在,一旦遇到符合条件的单词,它就会停止循环,而不是遍历整个数组,然后选择words[i]
距离最短的单词。
这word
只是函数中传递的随机单词。words
我正在使用的数组:
words: ["bed", "bank", "fence", "bridges"]
如果其中任何内容是居高临下的,请告诉我,或者如果你们都需要更多信息。
要查找数组中距离最短且小于阈值的单词,您需要:
return
在循环中,因为这会提前终止它)要删除
return
循环中间的 ,您应该跟踪到目前为止您所看到的最接近的单词。下面我将此单词存储在一个名为 的变量中closestWord
,以便您可以在循环完成后返回它(循环完成后,您已经查看了所有单词,因此您可以放心地说最接近的单词位于 中closestWord
)。您可以存储的另一件事(但不是强制性的)是计算出的距离closestWord
。下面我将其存储在closestDist
. 这使您可以确认为当前单词计算的距离小于(或等于,如果您想获取所看到的最后一个最近距离单词)迄今为止所看到的最近单词距离。从技术上讲,我们可以删除它,因为它可以通过调用并传入来closestDist
计算getDistanceByLength
closestWord
和word
,但这允许我们将其初始化为Infinity
,使循环中的比较逻辑更容易,因为第一次遇到小于更新阈值的单词时不需要特殊情况closestWord
: