Bloodhound 识别错误?

Bloodhound identify bug?

我使用的是最新版本的 typeahead.js (v0.11.1)。当对数据集值使用不同的 ID 时,我观察到奇怪的行为。

我创建了一个 JSFiddle。这是js代码:

var ds = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: [{id: 1, name: "a b 1"}, {id: 2, name: "a b 2"}, {id: 3, name: "a"}],
    identify: function(obj) { return obj.id; }
});

$('#go').typeahead(null, {
    name: 'ds',
    display: 'name',
    source: ds
});

现在,如果我更改 'local' 的数据,提前输入可能会出现故障。这里只是一些例子:

对 'local' 使用这些值之一(注意第三个元素是从“1”开始的随机数):

[{id: 1, 姓名: "a b 1"}, {id: 2, 姓名: "a b 2"}, {id: 15, 姓名: "a"}]

[{id: 1, 姓名: "a b 1"}, {id: 2, 姓名: "a b 2"}, {id: 1849, 姓名: "a"}]

现在,当我输入文本框:"a b" 时,预输入应该提示 "a b 1" 和 "a b 2",但实际上它只提示 "a b 1"。

这可以通过以下方法之一解决:

此外,如果我使用大于 2 的数字作为第一个元素的 id,如下所示:

[{id: 3, 姓名: "a b 1"}, {id: 2, 姓名: "a b 2"}, {id: 15, 姓名: "a"}]

现在当我在文本框中输入"a b"时,没有提示!

回答我自己的问题。是的,猎犬中有一个错误。 SearchIndex.getIntersection() 函数未正确实现。你可以把这个函数拿出来测试一下:

getIntersection([1,2,15],[1,2])

结果应该是return[1,2],但实际上是return[1]。这是因为它错误地使用了 sort() 函数来对数字进行排序。根据 w3schools:

By default, the sort() method sorts the values as strings in alphabetical and ascending order.

This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

所以这个函数可以通过改变这两行来修复:

        arrayA = arrayA.sort();
        arrayB = arrayB.sort();

进入:

        arrayA = arrayA.sort(function(a, b){return a-b});
        arrayB = arrayB.sort(function(a, b){return a-b});

我花了 1 天时间才弄明白:(