improved code readability

This commit is contained in:
Valerie Wolfe 2023-08-20 13:27:14 -04:00
parent 8abb3c778e
commit 351d845992

View file

@ -28,6 +28,7 @@ mod util;
pub const VERSION: &str = "0.2.0";
fn main() {
// build eval context
let mut context = context_map! {
// globals
"e" => global::EULER,
@ -53,8 +54,18 @@ fn main() {
"π" => global::PI,
"" => Function::new(|arg| helper::square_root(arg))
}.unwrap();
// collect args and evaluate if present
let expressions: Vec<String> = env::args().skip(1).collect();
if expressions.len() == 0 {
if expressions.len() > 0 {
for expression in expressions {
match expression.as_str() {
"help" => help_text(),
_ => do_eval(expression, &mut context)
}
}
} else {
// enter interactive mode if no args are given
println!("{}quickmaths v{}{}\n{}Interactive Mode{}", style::Bold, VERSION, style::Reset, style::Faint, style::Reset);
loop {
print!("> ");
@ -72,13 +83,6 @@ fn main() {
}
reset();
}
} else {
for expression in expressions {
match expression.as_str() {
"help" => help_text(),
_ => do_eval(expression, &mut context)
}
}
}
}
@ -86,12 +90,20 @@ fn do_eval(i_expression: String, context: &mut HashMapContext) {
let expression = i_expression.as_str();
let i_result = eval_with_context_mut(expression, context);
if i_result.is_err() {
println!("{}{}{}", color::Fg(color::Red), style::Bold, expression);
println!(
"{red}✕ {bold}{expression}",
bold = style::Bold,
red = color::Fg(color::Red)
);
return;
}
let result = i_result.ok().unwrap();
if result.is_empty() {
println!("{}{}{}", color::Fg(color::Green), style::Bold, expression);
println!(
"{green}✓ {bold}{expression}",
bold = style::Bold,
green = color::Fg(color::Green)
);
return;
}
let delimiter;
@ -100,7 +112,13 @@ fn do_eval(i_expression: String, context: &mut HashMapContext) {
Value::String(ref _str) => delimiter = "=>",
_ => delimiter = "="
}
println!("{}{}{}{} {} {}{}", style::Faint, style::Italic, expression, style::Reset, delimiter, style::Bold, result);
println!(
"{faint}{italic}{expression}{reset} {delimiter} {bold}{result}",
bold = style::Bold,
faint = style::Faint,
italic = style::Italic,
reset = style::Reset
);
}
fn reset() {
@ -109,9 +127,15 @@ fn reset() {
}
fn help_text() {
println!("{}quickmaths v{}{}", style::Bold, crate::VERSION, style::Reset);
println!("Valerie Wolfe <sleeplessval@gmail.com>");
println!("A mathematical expression evaluator written in Rust.\n");
println!("USAGE:");
println!("\tqm [EXPRESSION]...\n");
println!(
"{bold}quickmaths v{version}{reset}
Valerie Wolfe <sleeplessval@gmail.com>
A mathematical expression evaluator written in Rust.
usage:
qm [EXPRESSION]...",
bold = style::Bold,
reset = style::Reset,
version = crate::VERSION
);
}