added log function

This commit is contained in:
2024-04-15 10:14:49 +02:00
parent 7ea94f9cef
commit 6266b49fd5

View File

@@ -43,6 +43,7 @@ enum FunctionType {
Sine,
Cosine,
NaturalLog,
Log10,
Max,
Min,
SquareRoot,
@@ -153,6 +154,7 @@ impl std::fmt::Display for Token {
FunctionType::Max => write!(f, "max"),
FunctionType::Min => write!(f, "min"),
FunctionType::SquareRoot => write!(f, "sqrt"),
FunctionType::Log10 => write!(f, "log"),
},
}
}
@@ -223,6 +225,7 @@ fn parse_buffer(buf: &str) -> Result<Token, TokenizeError> {
"sin" => Ok(Token::Function(FunctionType::Sine)),
"cos" => Ok(Token::Function(FunctionType::Cosine)),
"ln" => Ok(Token::Function(FunctionType::NaturalLog)),
"log" => Ok(Token::Function(FunctionType::Log10)),
"max" => Ok(Token::Function(FunctionType::Max)),
"min" => Ok(Token::Function(FunctionType::Min)),
"sqrt" => Ok(Token::Function(FunctionType::SquareRoot)),
@@ -428,6 +431,7 @@ fn calculate(tokens: Vec<Token>) -> Result<f64, CalculateError> {
FunctionType::Sine => Some(n.sin()),
FunctionType::Cosine => Some(n.cos()),
FunctionType::NaturalLog => Some(n.ln()),
FunctionType::Log10 => Some(n.log10()),
FunctionType::SquareRoot => Some(n.sqrt()),
_ => None,
};
@@ -501,6 +505,14 @@ mod tests {
tokenize("sqrt"),
Ok(vec![Token::Function(FunctionType::SquareRoot)])
);
assert_eq!(
tokenize("ln"),
Ok(vec![Token::Function(FunctionType::Log10)])
);
assert_eq!(
tokenize("log"),
Ok(vec![Token::Function(FunctionType::Log10)])
);
assert_eq!(
tokenize("3.14159265358979323"),
Ok(vec![Token::Number(3.14159265358979323)])