Skip to content

Instantly share code, notes, and snippets.

@danielrw7
Created December 12, 2015 20:46
Show Gist options
  • Save danielrw7/0660b9eeafc48018c6c8 to your computer and use it in GitHub Desktop.
Save danielrw7/0660b9eeafc48018c6c8 to your computer and use it in GitHub Desktop.
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;
});
}
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