Created
November 24, 2018 10:01
-
-
Save andrei-cacio/4ea2e679bddf6ca9c0c37bf9aafd6a02 to your computer and use it in GitHub Desktop.
wasm1
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
extern crate cfg_if; | |
extern crate wasm_bindgen; | |
extern crate regex; | |
#[macro_use] | |
extern crate serde_derive; | |
use wasm_bindgen::prelude::*; | |
use regex::Regex; | |
#[wasm_bindgen] | |
pub fn fuzzy(query: &str, content: &str) -> String { | |
if query == "" { | |
return content.to_string(); | |
} | |
let rgx = Regex::new(query).unwrap(); | |
let res = rgx.replace_all(content, "<span class='match'>$0</span>"); | |
res.to_string() | |
} | |
#[derive(Deserialize, Serialize)] | |
pub struct Book { | |
author: String, | |
title: String | |
} | |
#[derive(Deserialize, Serialize)] | |
pub struct Books { | |
col: Vec<Book>, | |
} | |
#[wasm_bindgen] | |
pub fn filter_books(js_books: &JsValue, query: &str) -> JsValue { | |
let books: Books = js_books.into_serde().unwrap(); | |
let col: Vec<Book> = books.col | |
.into_iter() | |
.filter(|book| Regex::new(query).unwrap().is_match(&book.author) || Regex::new(query).unwrap().is_match(&book.title)) | |
.map(|mut book| { | |
book.author = fuzzy(query, &book.author); | |
book.title = fuzzy(query, &book.title); | |
book | |
}) | |
.collect(); | |
JsValue::from_serde(&Books { col }) | |
.unwrap() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment