Compare commits

..
Author SHA1 Message Date
3073205d90
refactor(formatting): use pre-stringified value 2026-11-15 20:11:13 -08:00

View file

@ -1,5 +1,3 @@
use rug::Float;
use crate::nodes::{self, Error}; use crate::nodes::{self, Error};
pub fn pretty_eval(input: &str, max_digits: usize) -> Result<String, Error> { pub fn pretty_eval(input: &str, max_digits: usize) -> Result<String, Error> {
@ -11,69 +9,22 @@ pub fn pretty_eval(input: &str, max_digits: usize) -> Result<String, Error> {
let should_add_back_backslash = input.contains('\\'); let should_add_back_backslash = input.contains('\\');
let result = nodes::eval(&input)?; let result = nodes::eval(&input)?;
let display_digits = get_significant_digits(&result).clamp(1, max_digits); let display_digits = get_significant_digits(result.to_string()).clamp(
if result >= 1000 || result < 1 {
// this helps improve the output formatting, 1
// by not using scientific notation when it doesn't make sense. } else if result >= 100 {
// 3
// it does this by parsing the string, which is unfortunate. } else if result >= 10 {
// ideally, this would be done by reimplementing the display code; 2
// but neither I nor Edeth know how to do that yet. // if result >= 1
// (much like with `get_significant_digits`)
let mut changing_string = format!("{result:.display_digits$}");
if let Some(index) = changing_string.find('e')
&& ((changing_string.chars().nth(index + 1).unwrap() == '-'
&& changing_string
.chars()
.nth(index + 2)
.unwrap()
.to_digit(10)
.unwrap()
< 6
&& changing_string.len() - index == 3)
|| (changing_string.chars().nth(index + 1).unwrap() != '-'
&& changing_string
.chars()
.nth(index + 1)
.unwrap()
.to_digit(10)
.unwrap()
< 6
&& changing_string.len() - index == 2))
{
let exponent: isize = changing_string[index + 1..].parse().unwrap();
changing_string.drain(index..);
if exponent > 0 {
let uexp = exponent as usize;
if let Some(dot_pos) = changing_string.find('.') {
if changing_string.len() - dot_pos - 1 == uexp {
changing_string.remove(dot_pos);
} else if changing_string.len() - dot_pos - 1 > uexp {
let new_pos = dot_pos + uexp;
changing_string.remove(dot_pos);
changing_string.insert(new_pos, '.');
} else { } else {
let amount_of_zeros = uexp - (changing_string.len() - dot_pos - 1); 1
changing_string.remove(dot_pos); },
changing_string.push_n('0', amount_of_zeros); max_digits,
}
} else {
changing_string.push_n('0', uexp);
}
} else {
let uexp = exponent.unsigned_abs();
if let Some(dot_pos) = changing_string.find('.') {
changing_string.remove(dot_pos);
}
changing_string.insert_str(
if changing_string.contains('-') { 1 } else { 0 },
&format!("0.{}", "0".repeat(uexp - 1)),
); );
}
}
Ok(format!( Ok(format!(
"{prefix}{deliminator}{changing_string}{}", "{prefix}{deliminator}{result:.display_digits$}{}",
if should_add_back_backslash { " \\" } else { "" } if should_add_back_backslash { " \\" } else { "" }
) )
.replace('e', " * 10^")) .replace('e', " * 10^"))
@ -92,19 +43,9 @@ impl StrExt for str {
.unwrap_or(("", "", self)) .unwrap_or(("", "", self))
} }
} }
trait StringExt {
fn push_n(&mut self, c: char, n: usize);
}
impl StringExt for String {
fn push_n(&mut self, c: char, n: usize) {
for _ in 0..n {
self.push(c);
}
}
}
pub fn get_significant_digits(n: &Float) -> usize { pub fn get_significant_digits(n: impl AsRef<str>) -> usize {
let raw_string = n.to_string().replace(['.', '-'], ""); let raw_string = n.as_ref().replace(['.', '-'], "");
let mut consecutive_zeros = 0; let mut consecutive_zeros = 0;
let mut consecutive_nines = 0; let mut consecutive_nines = 0;
@ -139,7 +80,7 @@ pub fn get_significant_digits(n: &Float) -> usize {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
fn eval(s: &str) -> Float { fn eval(s: &str) -> rug::Float {
crate::nodes::eval(s).unwrap() crate::nodes::eval(s).unwrap()
} }
macro_rules! assert_pretty_eval { macro_rules! assert_pretty_eval {
@ -169,7 +110,7 @@ mod tests {
assert_pretty_eval!("10"); assert_pretty_eval!("10");
assert_pretty_eval!("100"); assert_pretty_eval!("100");
assert_pretty_eval!("999"); assert_pretty_eval!("999");
assert_pretty_eval!("1000"); assert_pretty_eval!("1000", "1 * 10^3");
assert_pretty_eval!("11.111111"); assert_pretty_eval!("11.111111");
} }
@ -197,22 +138,6 @@ mod tests {
assert_pretty_eval!("10_000 * 10_000 * 4", "4 * 10^8") assert_pretty_eval!("10_000 * 10_000 * 4", "4 * 10^8")
} }
#[test]
fn prettier_sci_notation() {
assert_pretty_eval!("1 * 10^6");
assert_pretty_eval!("10^5", "100000");
assert_pretty_eval!("1 * 10^(-6)", "1 * 10^-6");
assert_pretty_eval!("10^(-5)", "0.00001");
assert_pretty_eval!("0.0001");
assert_pretty_eval!("1.0901");
assert_pretty_eval!("10901");
}
#[test]
fn formatting_minus() {
assert_pretty_eval!("1/(2^3 * (-1)^(2 - 1))", "-0.125");
}
#[test] #[test]
fn basic_get_significant_digits() { fn basic_get_significant_digits() {
let many_zeros = eval("14.00643 + 1.00784 * 4 + 35.446 + 15.9994 * 4"); let many_zeros = eval("14.00643 + 1.00784 * 4 + 35.446 + 15.9994 * 4");
@ -224,9 +149,9 @@ mod tests {
let test_4 = eval("12.0096 + 1.00784 * 3 + 12.0096 + 1.00784 * 2 + 15.9994 + 1.00784"); let test_4 = eval("12.0096 + 1.00784 * 3 + 12.0096 + 1.00784 * 2 + 15.9994 + 1.00784");
assert_eq!(test_4.to_f64(), 46.06564); assert_eq!(test_4.to_f64(), 46.06564);
assert_eq!(get_significant_digits(&many_zeros), 8); assert_eq!(get_significant_digits(many_zeros.to_string()), 8);
assert_eq!(get_significant_digits(&many_nines), 6); assert_eq!(get_significant_digits(many_nines.to_string()), 6);
assert_eq!(get_significant_digits(&zero_nine_zero), 6); assert_eq!(get_significant_digits(zero_nine_zero.to_string()), 6);
assert_eq!(get_significant_digits(&test_4), 7); assert_eq!(get_significant_digits(test_4.to_string()), 7);
} }
} }