Last active
August 29, 2015 14:13
-
-
Save panchr/8dc2a82466454ed5575a to your computer and use it in GitHub Desktop.
GitHub repository sorting
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
/* | |
repositories is a list of repository objects, in the form of | |
[ | |
{name: "repo A", description: "my first repository!"}, | |
{name: "repo B", description: "my second repository!"} | |
] | |
This is the same form as returned by the GitHub API: https://api.github.com/users/panchr/repos | |
query is just the search query as a string, such as "repo python my first" | |
*/ | |
function rankRepositories(repositories, query) { | |
// Rank the repositories based on query | |
var queryWords = query.split(" ").filter(function (string) { | |
return string.length > 1; | |
}); | |
var re = new RegExp(queryWords.join("|"), "gi"); | |
var sortedRepositories = repositories | |
.filter(function (elem) { | |
return re.test(elem.name) || re.test(elem.description); | |
}) | |
.sort(function (a, b) { | |
var rankA = repositoryRank(a, re); | |
var rankB = repositoryRank(b, re); | |
if (rankA < rankB) return 1; | |
else if (rankA > rankB) return -1; | |
else return 0; | |
}); | |
return sortedRepositories; | |
} | |
function repositoryRank(repo, re) { | |
// Returns a repository's rank | |
return 5 * regexSimilarity(re, repo.name) + regexSimilarity(re, repo.description); | |
} | |
function regexSimilarity(re, string) { | |
// Returns the regex similarity for a string | |
var matches = string.match(re); | |
return (matches ? matches.length: 0) / string.length; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment