Created
July 21, 2016 21:12
-
-
Save juanka881/bf0b6c491e7764a8f21be4f2ac99fdbc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function fuzzyMatch(searchSet, query) { | |
| var tokens = query.toLowerCase().split(''), | |
| matches = []; | |
| searchSet.forEach(function(string) { | |
| var tokenIndex = 0, | |
| stringIndex = 0, | |
| matchWithHighlights = '', | |
| matchedPositions = []; | |
| string = string.toLowerCase(); | |
| while (stringIndex < string.length) { | |
| if (string[stringIndex] === tokens[tokenIndex]) { | |
| matchWithHighlights += highlight(string[stringIndex]); | |
| matchedPositions.push(stringIndex); | |
| tokenIndex++; | |
| if (tokenIndex >= tokens.length) { | |
| matches.push({ | |
| match: string, | |
| highlighted: matchWithHighlights + string.slice(stringIndex + 1), | |
| positions: matchedPositions | |
| }); | |
| break; | |
| } | |
| } | |
| else { | |
| matchWithHighlights += string[stringIndex]; | |
| } | |
| stringIndex++; | |
| } | |
| }); | |
| return matches; | |
| } | |
| function highlight(string) { | |
| return '<span class="highlight">' + string + '</span>'; | |
| } | |
| function search() { | |
| var query = $('input').first().val(), | |
| searchSet = $('textarea').first().val().split('\n'), | |
| matches = fuzzyMatch(searchSet, query), | |
| $resultList = $('ul'); | |
| $resultList.empty(); | |
| matches.forEach(function(match) { | |
| $('<li/>').html(match.highlighted).appendTo($resultList); | |
| console.log('Match: ', match); | |
| }); | |
| } | |
| $('a').click(function() { | |
| search(); | |
| return false; | |
| }); | |
| $('input').keydown(function(e) { | |
| if (e.which === 13) { | |
| search(); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment