vortaroboto

Log | Files | Refs | README

stats.rs (1927B)


      1 use std::collections::HashMap;
      2 use crate::pack::{pack_data, unpack_data};
      3 use crate::requests::difinu;
      4 use super::Command;
      5 
      6 const VORTO_PATH: &'static str = "vorto.bincode";
      7 pub async fn add_words(frazo: String) {
      8     let mut h: HashMap<String, usize> = unpack_data(VORTO_PATH).unwrap_or_default();
      9 
     10     for vorto in frazo.split_ascii_whitespace() {
     11         if let Ok(tro) = difinu(vorto.to_owned()).await {
     12             if let Some(vf) = tro
     13                 .vortfarado
     14                 .iter()
     15                 .filter(|vf| vf.partoj.len() > 1)
     16                 .next()
     17             {
     18                 let mut vera_vorto = String::with_capacity(vorto.len());
     19 
     20                 if vf.partoj.len() > 1 {
     21                     // Konstrui la vera vorto
     22                     // sen la termnoj
     23                     for p in vf.partoj.iter().take_while(|p| p.vorto.is_some()) {
     24                         vera_vorto.push_str(p.parto.as_str());
     25                     }
     26                     vera_vorto.push('-');
     27                 } else {
     28                     // vorto estas la vera, nura, vorto
     29                     vera_vorto = vorto.to_owned()
     30                 }
     31 
     32                 if let Some(v) = h.get_mut(&vera_vorto) {
     33                     *v += 1;
     34                 } else {
     35                     h.insert(vera_vorto, 1);
     36                 }
     37             }
     38         }
     39     }
     40 
     41     pack_data(VORTO_PATH, &h).unwrap(); // Tre neebla, sed...
     42 }
     43 
     44 pub fn stats() -> Result<String, String> {
     45     let mut h: HashMap<String, usize> = unpack_data(VORTO_PATH)?;
     46     let mut h: Vec<(String, usize)> = h.drain().collect();
     47     h.sort_by_cached_key(|(_, s)| *s);
     48     h.reverse();
     49 
     50     Ok(h.iter()
     51         .take(10)
     52         .map(|(v, o)| format!("{}: {}", v, o))
     53         .collect::<Vec<String>>()
     54         .join(", "))
     55 }
     56 
     57 pub const STAT_CMD: Command = Command {
     58     name: "statistiko",
     59     description: "Donu la 10 vortoj plej uzataj.",
     60     args: &[],
     61     opt_args: &[],
     62 };