String matching and ranking algorithm for autocomplete
npm install kindalikeThis library implements an algorithm that is suitable for autocompletion.
The kindalike function takes a search string and an array of subject strings to search in:
``javascript
var query = somethingTheUserTypes();
var subjects = someArrayOfStrings();
// matches is an Array where each element is an object
// with properties subject, indices and gaps
var matches = kindalike(query, subjects);
`
Each match is an object like so:
`javascript`
{ subject: 'horse', indices: [1, 4], gaps: 2 }
The subject property is the matched subject.
The indices property is an array of int, each representing the index in the subjectoe
where a query character is found. In the example above the query string was , and[1, 4]
each of those letters were found at indices .
The gaps property is a number indicating how many gaps there are between letters from the2
query string. In this case there was a gap of - between index 1 and 4.
The matches are sorted by the gaps property, ranking matches with small gaps higher. Subjects that don't
match all the characters in the query are excluded.
Each match can be turned into string with elements around each matched character:
`javascript`
var html = kindalike.spans({ subject: 'horse', indices: [1, 4], gaps: 2 })
Returns:
``
horse
By styling the element this can be used to highlight the letters from the query.
Just open index.html` in a browser.