Skip to content

Instantly share code, notes, and snippets.

@BruJu
Created May 6, 2020
Embed
What would you like to do?
IntVect
extern crate wasm_bindgen;
extern crate js_sys;
use wasm_bindgen::prelude::*;
use std::collections::BTreeSet;
#[wasm_bindgen]
pub struct IntVector {
values: Vec<i32>
}
#[wasm_bindgen]
impl IntVector {
#[wasm_bindgen(constructor)]
pub fn new() -> IntVector {
IntVector { values: vec!() }
}
pub fn fill(&mut self, passed_values: &js_sys::Array) {
for x in passed_values.keys() {
let x = x.unwrap().as_f64().unwrap() as i32;
self.values.push(x);
}
self.values.sort();
}
pub fn find(&self, searched_value: i32) -> bool {
self.values.iter().find(|&&x| x == searched_value).is_some()
}
pub fn binary_search(&self, searched_value: i32) -> bool {
self.values.binary_search(&searched_value).is_ok()
}
pub fn extract_superior_to(&self, searched_value: i32) -> IntVector {
let mut new_vector = IntVector::new();
for i in self.values.iter() {
if i >= &searched_value {
new_vector.values.push(*i);
}
}
new_vector
}
pub fn median(&self) -> i32 {
self.values[self.values.len() / 2]
}
}
#[wasm_bindgen]
pub struct IntTree {
values: BTreeSet<i32>
}
#[wasm_bindgen]
impl IntTree {
#[wasm_bindgen(constructor)]
pub fn new() -> IntTree {
IntTree { values: BTreeSet::new() }
}
pub fn fill(&mut self, passed_values: &js_sys::Array) {
for x in passed_values.keys() {
let x = x.unwrap().as_f64().unwrap() as i32;
self.values.insert(x);
}
}
pub fn binary_search(&self, searched_value: i32) -> bool {
self.values.contains(&searched_value)
}
pub fn extract_superior_to(&self, searched_value: i32) -> IntTree {
let mut new_tree = IntTree::new();
for i in self.values.range(searched_value..) {
if i >= &searched_value {
new_tree.values.insert(*i);
}
}
new_tree
}
pub fn to_intvec(&self) -> IntVector {
let mut new_vec = IntVector::new();
for i in self.values.iter() {
new_vec.values.push(*i);
}
new_vec
}
pub fn median(&self) -> i32 {
let intvec = self.to_intvec();
intvec.median()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment