-
Notifications
You must be signed in to change notification settings - Fork 100
/
lib.rs
60 lines (50 loc) · 1.76 KB
/
lib.rs
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
use wasm_bindgen::prelude::*;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: f32,
y: f32
}
#[derive(Serialize, Deserialize, Debug)]
struct Line {
points: Vec<Point>,
valid: bool,
length: f32,
desc: String
}
// Compute the circumference given the radius
#[wasm_bindgen]
pub fn circumference(radius: &str) -> String {
let r: f32 = serde_json::from_str(radius).unwrap();
let c = 2. * 3.14159 * r;
return serde_json::to_string(&c).unwrap();
}
// Compute the area given the width and length of a rectangle
#[wasm_bindgen]
pub fn area(sides: &str) -> String {
let s: (f32, f32) = serde_json::from_str(&sides).unwrap();
let a = s.0 * s.1;
return serde_json::to_string(&a).unwrap();
}
// Solve a quadratic equation https://www.mathsisfun.com/quadratic-equation-solver.html
#[wasm_bindgen]
pub fn solve(params: &str) -> String {
let ps: (f32, f32, f32) = serde_json::from_str(¶ms).unwrap();
let discriminant: f32 = (ps.1 * ps.1) - (4. * ps.0 * ps.2);
let mut solution: (f32, f32, bool) = (0., 0., false);
if discriminant >= 0. {
solution.0 = (((-1.) * ps.1) + discriminant.sqrt()) / (2. * ps.0);
solution.1 = (((-1.) * ps.1) - discriminant.sqrt()) / (2. * ps.0);
solution.2 = true;
}
return serde_json::to_string(&solution).unwrap();
}
// Draw a line between two points
#[wasm_bindgen]
pub fn draw(points: &str) -> String {
let ps: (Point, Point, String) = serde_json::from_str(&points).unwrap();
let length = ((ps.0.x - ps.1.x) * (ps.0.x - ps.1.x) + (ps.0.y - ps.1.y) * (ps.0.y - ps.1.y)).sqrt();
let valid = if length == 0.0 { false } else { true };
let line = Line { points: vec![ps.0, ps.1], valid: valid, length: length, desc: ps.2 };
return serde_json::to_string(&line).unwrap();
}