improve handling of $base to math.log

This commit is contained in:
Connor Skees 2021-07-25 16:34:09 -04:00
parent 1c553fd8dc
commit 2e1fa7ca2c
3 changed files with 23 additions and 4 deletions

View File

@ -225,7 +225,7 @@ fn log(mut args: CallArgs, _: &mut Parser) -> SassResult<Value> {
if base.is_zero() { if base.is_zero() {
Some(Number::zero()) Some(Number::zero())
} else { } else {
(|| Some(number.ln()? / base.ln()?))() number.log(base)
} }
} else if number.is_negative() { } else if number.is_negative() {
None None

View File

@ -29,8 +29,12 @@ impl PartialEq for Number {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
match (self, other) { match (self, other) {
(Number::Small(val1), Number::Small(val2)) => val1 == val2, (Number::Small(val1), Number::Small(val2)) => val1 == val2,
(Number::Big(val1), val2 @ Number::Small(..)) => **val1 == val2.clone().into_big_rational(), (Number::Big(val1), val2 @ Number::Small(..)) => {
(val1 @ Number::Small(..), Number::Big(val2)) => val1.clone().into_big_rational() == **val2, **val1 == val2.clone().into_big_rational()
}
(val1 @ Number::Small(..), Number::Big(val2)) => {
val1.clone().into_big_rational() == **val2
}
(Number::Big(val1), Number::Big(val2)) => val1 == val2, (Number::Big(val1), Number::Big(val2)) => val1 == val2,
} }
} }
@ -135,7 +139,7 @@ impl Number {
} }
#[allow(clippy::cast_precision_loss)] #[allow(clippy::cast_precision_loss)]
fn as_float(self) -> Option<f64> { pub fn as_float(self) -> Option<f64> {
Some(match self { Some(match self {
Number::Small(n) => ((*n.numer() as f64) / (*n.denom() as f64)), Number::Small(n) => ((*n.numer() as f64) / (*n.denom() as f64)),
Number::Big(n) => ((n.numer().to_f64()?) / (n.denom().to_f64()?)), Number::Big(n) => ((n.numer().to_f64()?) / (n.denom().to_f64()?)),
@ -154,6 +158,12 @@ impl Number {
)?))) )?)))
} }
pub fn log(self, base: Number) -> Option<Self> {
Some(Number::Big(Box::new(BigRational::from_float(
self.as_float()?.log(base.as_float()?),
)?)))
}
pub fn pow(self, exponent: Self) -> Option<Self> { pub fn pow(self, exponent: Self) -> Option<Self> {
Some(Number::Big(Box::new(BigRational::from_float( Some(Number::Big(Box::new(BigRational::from_float(
self.as_float()?.powf(exponent.as_float()?), self.as_float()?.powf(exponent.as_float()?),

View File

@ -598,3 +598,12 @@ test!(
"@use 'sass:math';\na {\n color: math.div(\"1\",\"2\");\n}\n", "@use 'sass:math';\na {\n color: math.div(\"1\",\"2\");\n}\n",
"a {\n color: \"1\"/\"2\";\n}\n" "a {\n color: \"1\"/\"2\";\n}\n"
); );
test!(
log_returns_whole_number_for_simple_base,
"@use 'sass:math';
a {
color: math.log(8, 2);
color: math.floor(math.log(8, 2));
}",
"a {\n color: 3;\n color: 3;\n}\n"
);