-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathslash_command_ranking.cpp
More file actions
68 lines (56 loc) · 1.96 KB
/
Copy pathslash_command_ranking.cpp
File metadata and controls
68 lines (56 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "slash_command_ranking.hpp"
#include <algorithm>
#include <utility>
namespace acecode {
namespace {
int match_score(std::string_view query,
std::string_view name,
std::string_view description) {
if (query.empty()) return 1;
if (name == query) return 200;
if (name.rfind(query, 0) == 0) return 100;
if (name.find(query) != std::string_view::npos) return 50;
if (description.find(query) != std::string_view::npos) return 10;
return 0;
}
struct RankedCandidate {
int match_score = 0;
std::uint64_t usage_count = 0;
SlashCommandCandidate candidate;
};
} // namespace
std::vector<SlashCommandCandidate> rank_slash_command_candidates(
std::string_view query,
const std::vector<SlashCommandCandidate>& candidates,
const SlashCommandUsageCounts& usage_counts) {
std::vector<RankedCandidate> ranked;
ranked.reserve(candidates.size());
for (const auto& candidate : candidates) {
const int score = match_score(
query, candidate.name, candidate.description);
if (score == 0) continue;
const auto usage = usage_counts.find(candidate.name);
ranked.push_back({
score,
usage == usage_counts.end() ? 0 : usage->second,
candidate,
});
}
std::sort(ranked.begin(), ranked.end(),
[](const RankedCandidate& a, const RankedCandidate& b) {
if (a.match_score != b.match_score) {
return a.match_score > b.match_score;
}
if (a.usage_count != b.usage_count) {
return a.usage_count > b.usage_count;
}
return a.candidate.name < b.candidate.name;
});
std::vector<SlashCommandCandidate> result;
result.reserve(ranked.size());
for (auto& item : ranked) {
result.push_back(std::move(item.candidate));
}
return result;
}
} // namespace acecode