Skip to content

Commit 6fbf19a

Browse files
committed
[AutoComplete] use sublime text like search instead of Levenshtein Distance for fuzzy search
1 parent 293865b commit 6fbf19a

2 files changed

Lines changed: 24 additions & 6 deletions

File tree

src/AutoComplete/AutoComplete.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -539,14 +539,17 @@ AutoComplete.levenshteinDistanceFilter = (distanceLessThan) => {
539539
};
540540

541541
AutoComplete.fuzzyFilter = (searchText, key) => {
542-
if (searchText.length === 0) {
543-
return false;
544-
}
542+
const compareString = key.toLowerCase();
543+
searchText = searchText.toLowerCase();
545544

546-
const subMatchKey = key.substring(0, searchText.length);
547-
const distance = AutoComplete.levenshteinDistance(searchText.toLowerCase(), subMatchKey.toLowerCase());
545+
let searchTextIndex = 0;
546+
for (let index = 0; index < key.length; index++) {
547+
if (compareString[index] === searchText[searchTextIndex]) {
548+
searchTextIndex += 1;
549+
}
550+
}
548551

549-
return searchText.length > 3 ? distance < 2 : distance === 0;
552+
return searchTextIndex === searchText.length;
550553
};
551554

552555
AutoComplete.Item = MenuItem;
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/* eslint-env mocha */
2+
import {assert} from 'chai';
3+
import AutoComplete from './AutoComplete';
4+
5+
describe('<AutoComplete />', () => {
6+
it('search using fuzzy filter', () => {
7+
assert.strictEqual(AutoComplete.fuzzyFilter('ea', 'Peach'), true, 'should match Peach with ea');
8+
assert.strictEqual(AutoComplete.fuzzyFilter('pah', 'Peach'), true, 'should match Peach with pah');
9+
assert.strictEqual(AutoComplete.fuzzyFilter('peach', 'Peach'), true, 'should match Peach with peach');
10+
11+
assert.strictEqual(AutoComplete.fuzzyFilter('phc', 'Peach'), false, 'should not match Peach with phc');
12+
assert.strictEqual(AutoComplete.fuzzyFilter('pp', 'Peach'), false, 'should not match Peach with pp');
13+
assert.strictEqual(AutoComplete.fuzzyFilter('pb', 'Peach'), false, 'should not match Peach with pb');
14+
});
15+
});

0 commit comments

Comments
 (0)