Created
October 31, 2017 16:20
-
-
Save alextanhongpin/5bf6d497af2615f8dc1e4583fb9617d8 to your computer and use it in GitHub Desktop.
Experimenting autocomplete in js using Jaccard Similarity
This file contains 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
const collection = ['food', 'car', 'paper', 'javascript', 'blockchain'] | |
function search (keyword) { | |
return collection.filter((val) => val.toLowerCase().includes(keyword.toLowerCase())) | |
} | |
function autocorrectSearch (keyword) { | |
if (!search(keyword).length) { | |
const output = collection.filter((val) => { | |
const keywords = keyword.split('') | |
const values = val.split('') | |
const score = jaccardSimilarity1(keywords, values) | |
const score2 = jaccardSimilarity2(keywords, values) | |
console.log(score, score2) | |
return score > 0.5 | |
}) | |
return output | |
} | |
return keyword | |
} | |
function jaccardSimilarity1 (arr1, arr2) { | |
const union = [...new Set(arr1.concat(arr2))] | |
const intersect = arr1.filter((val) => arr2.includes(val)) | |
return intersect.length / union.length | |
} | |
function jaccardSimilarity2 (arr1, arr2) { | |
const uniqueA = [...new Set(arr1)] | |
const uniqueB = [...new Set(arr2)] | |
const union = [...new Set(uniqueA.concat(uniqueB))] | |
const intersect = uniqueA.filter((val) => uniqueB.includes(val)) | |
return intersect.length / union.length | |
} | |
console.log('search:', search('jaa')) | |
console.log('autocorrect:', autocorrectSearch('blckch')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment