Created
December 12, 2015 20:46
-
-
Save danielrw7/0660b9eeafc48018c6c8 to your computer and use it in GitHub Desktop.
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
RegExp.escape = function(text) { | |
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); | |
} | |
function searchScore(query, data) { | |
var query = query.toString().replace(/\s+/g, " "); | |
var queryRegEx = new RegExp(RegExp.escape(query), "g"); | |
function uniqueArray(array) { | |
var result = []; | |
for(var i in array) { | |
if (result.indexOf(array[i]) === -1) { | |
result.push(array[i]); | |
} | |
} | |
return result; | |
} | |
function getScore(data) { | |
if (typeof data !== 'object') { | |
data = {value: data}; | |
} | |
data.score = 0; | |
var words = uniqueArray(query.replace(/\s+/g, ' ').split(/\s/g)); | |
for(var key in data) { | |
var val = data[key].toString(); | |
var fullMatches = val.match(queryRegEx) || []; | |
if (fullMatches && fullMatches.length >= 1) { | |
data.score += fullMatches.length; | |
} else { | |
data.score += words.map(function(str) { | |
return (val.match(new RegExp(RegExp.escape(str), "g")) || []).length/words.length*0.9 || 0; | |
}).reduce(function(a, b) { | |
return a + b; | |
}); | |
} | |
} | |
return data; | |
} | |
return arguments.length > 1 ? getScore(data) : getScore; | |
} | |
function search(query, rows) { | |
return rows.map(searchScore(query)).sort(function(a, b) { | |
return a.score < b.score; | |
}); | |
} |
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
search("test", ["test1", "test2"]); | |
// => [{"value":"test1","score":1},{"value":"test2","score":1}] | |
search("test this", [{ | |
key: "value", | |
anotherKey: "test" | |
}, { | |
key: "test this", | |
anotherKey: "this test" | |
}]); | |
// => [{"key":"test this","anotherKey":"this test","score":1.9},{"key":"value","anotherKey":"test","score":0.45}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment