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
#[macro_use] extern crate lazy_static; use std::cmp::Reverse; use std::collections::HashSet; use std::error::Error; use std::path::PathBuf; use tinysearch_shared::{Filters, Score, Storage}; use wasm_bindgen::prelude::*; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; fn load_filters() -> Result<Filters, Box<Error>> { let bytes = include_bytes!("../storage"); Ok(Storage::from_bytes(bytes)?.filters) } lazy_static! { static ref FILTERS: Filters = load_filters().unwrap(); } #[wasm_bindgen] pub fn search(query: String, num_results: usize) -> JsValue { let search_terms: HashSet<String> = query.split_whitespace().map(|s| s.to_lowercase()).collect(); let mut matches: Vec<(&PathBuf, u32)> = FILTERS .iter() .map(|(name, filter)| (name, filter.score(&search_terms))) .filter(|(_, score)| *score > 0) .collect(); matches.sort_by_key(|k| Reverse(k.1)); let results: Vec<&PathBuf> = matches .iter() .map(|(name, _)| name.to_owned()) .take(num_results) .collect(); JsValue::from_serde(&results).unwrap() }