Multi-Step Calculator

This example implements a multi-step calculator bot. Users can send arithmetic expressions in multiple consecutive messages and get the final result. For instance, if the user sends 1+1, the bot will return 2. The user can then send *3, and the bot will return 6.

Refer to multi-step-calculator for a complete code example.


#![allow(unused)]
fn main() {
use wasm_bindgen::prelude::*;
use meval;

#[wasm_bindgen]
pub fn text_received(msg: String, _user_info: String, step_data: String) -> String {
  if msg == "#" {
    return format!(r#"{{"new_step": true}}"#);
  } else {
    let exp = match step_data == ""{
      true => msg,
      _ => format!("({}){}", step_data, msg)
    };
    let x = meval::eval_str(&exp).unwrap();
    return format!(r#"{{"result": "{}", "step": "{}"}}"#, x, exp);
  }
}
}

The example code uses the meval crate for calculation. It also uses step because the bot required multi-step calculation. The return JSON value from every function call will include all the previous arithmetic expressions in step_data.