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
69
70
71
72
73
74
75
76
77
#![cfg(feature = "search")]
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd, Reverse};
use std::vec::Vec;
use crate::Emoji;
#[derive(Debug, Clone, Copy)]
struct Score(f64);
impl PartialEq for Score {
fn eq(&self, other: &Self) -> bool {
self.0.eq(&other.0)
}
}
impl Eq for Score {}
impl PartialOrd for Score {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Score {
fn cmp(&self, other: &Self) -> Ordering {
self.0.partial_cmp(&other.0).unwrap()
}
}
fn similarity(a: &str, b: &str) -> Score {
Score(strsim::jaro(a, b))
}
fn emoji_score(emoji: &Emoji, query: &str) -> Option<Score> {
let mut scores = Vec::new();
scores.push(similarity(emoji.name(), query));
if let Some(aliases) = emoji.aliases {
for alias in aliases {
scores.push(similarity(alias, query))
}
}
let score = scores.into_iter().max().unwrap();
if score.0 > 0.8 {
Some(score)
} else {
None
}
}
pub fn search(query: &str) -> impl Iterator<Item = &'static Emoji> {
let mut emojis: Vec<_> = crate::generated::EMOJIS
.iter()
.filter_map(|emoji| emoji_score(emoji, query).map(|s| (emoji, s)))
.collect();
emojis.sort_by_key(|(emoji, score)| (Reverse(*score), emoji.id));
emojis
.into_iter()
.map(|(emoji, _)| emoji)
.collect::<Vec<_>>()
.into_iter()
}