use super::arithmetic::eval;
use crate::{Context, Outcome, Plugin, number, re};
pub struct Percentages;
fn val(s: &str) -> Option<f64> {
let s = s.trim().replace(',', "");
s.parse::<f64>()
.ok()
.filter(|x| x.is_finite())
.or_else(|| eval(&s))
.or_else(|| {
let s = super::syntax::ungroup(&s);
if !re!(r"% (?:of|on|off) ").is_match(s) {
return None;
}
super::units::Units::default()
.expression(s, 0)
.ok()
.filter(|q| q.unit.dimension == [0; 8])
.map(|q| q.base)
})
}
fn out(n: f64, suffix: &str) -> Outcome {
n.is_finite().then(|| Ok(format!("{}{suffix}", number(n))))
}
impl Plugin for Percentages {
fn evaluate(&self, input: &str, _: &Context) -> Outcome {
let mut s = input
.to_lowercase()
.replace("per cent", "%")
.replace("percentage", "%")
.replace("percent", "%");
s = s
.replace("as discount", "as %")
.replace("what discount", "what %");
s = re!(r"% (?:exactly|precisely|take) ")
.replace_all(&s, "% ")
.into_owned();
s = re!(r" (?:as (?:a )?|is )% ")
.replace_all(&s, " is what % ")
.into_owned();
if let Some(c) = re!(r"^(.+?)% (of|on|off) what is (.+)$").captures(&s) {
s = format!("{} is {}% {} what", &c[3], &c[1], &c[2]);
}
if let Some(c) = re!(r"^what % is (.+?) with (.+)$").captures(&s) {
s = format!("{} is what % with {}", &c[1], &c[2]);
}
if let Some(c) = re!(r"^(.+) is what % with (.+)$").captures(&s) {
let a = val(&c[1])?;
let parts = c[2].replace(" and ", ",");
let total = parts
.split(',')
.map(val)
.collect::<Option<Vec<_>>>()?
.into_iter()
.sum::<f64>();
return out(a / (a + total) * 100.0, "%");
}
if let Some(c) = re!(r"^(.+) is what % after (?:adding )?(.+)$").captures(&s) {
let (a, b) = (val(&c[1])?, val(&c[2])?);
return out(b / (a - b) * 100.0, "%");
}
if let Some(c) = re!(r"^(?:if )?(.+?) is (.+?),? what is (.+)$").captures(&s)
&& s.contains('%')
{
let (a, p) = if let Some(p) = c[2].trim_end_matches(',').strip_suffix('%') {
(val(&c[1])?, val(p)?)
} else {
let p = c[1].strip_suffix('%')?;
(val(c[2].trim_end_matches(','))?, val(p)?)
};
let (n, suffix) = if let Some(target) = c[3].strip_suffix('%') {
(a / p * val(target)?, "")
} else {
(val(&c[3])? / a * p, "%")
};
return Some(if n.is_finite() {
Ok(format!("{}{suffix}", number(n)))
} else {
Err(crate::Error("internal_error".into()))
});
}
for word in ["increase ", "decrease ", "discount ", "tax "] {
if !s.starts_with('%') {
s = s.replace(word, "");
}
}
s = s.replace("ten %", "10%").replace("off of ", "of ");
let phrase = re!(r"([+-]?[\d.,]+)\s*% (of|on|off) ");
let mut rewritten = String::new();
let mut at = 0;
for c in phrase.captures_iter(&s) {
let m = c.get(0)?;
if m.start() < at {
continue;
}
let tail = &s[m.end()..];
let end = if tail.starts_with('(') {
let mut nesting = 0;
tail.char_indices().find_map(|(i, ch)| {
if ch == '(' {
nesting += 1;
} else if ch == ')' {
nesting -= 1;
}
(nesting == 0).then_some(i + ch.len_utf8())
})
} else {
re!(r"^[+-]?[\d.]+").find(tail).map(|m| m.end())
};
let Some(end) = end else {
continue;
};
if tail[end..].starts_with('%') {
continue;
}
let binary_sign = c[1].starts_with(['+', '-'])
&& s[..m.start()]
.trim_end()
.chars()
.last()
.is_some_and(|ch| ch.is_ascii_digit() || matches!(ch, ')' | '%'));
let start = m.start() + usize::from(binary_sign);
let p = val(if binary_sign { &c[1][1..] } else { &c[1] })? / 100.0;
let n = val(&tail[..end])?
* match &c[2] {
"on" => 1.0 + p,
"off" => 1.0 - p,
_ => p,
};
rewritten.push_str(&s[at..start]);
rewritten.push_str(&format!("({n})"));
at = m.end() + end;
}
if at > 0 && !s.ends_with(" -0") {
rewritten.push_str(&s[at..]);
if let Some(v) = eval(&rewritten) {
return out(v, "");
}
}
if let Some(c) = re!(r"^(.+) is (.+?)\s*% (of|on|off) what$").captures(&s) {
let (a, p) = (val(&c[1])?, val(&c[2])? / 100.0);
if p < 0.0 {
return None;
}
return out(
a / match &c[3] {
"on" => 1.0 + p,
"off" => 1.0 - p,
_ => p,
},
"",
);
}
if let Some(c) = re!(r"^(.+) is what\s*% (of|on|off) (.+)$").captures(&s) {
let (a, b) = (val(&c[1])?, val(&c[3])?);
if c[3].trim() == "-0" {
return None;
}
if b == 0.0 {
return Some(Err(crate::Error("null_result".into())));
}
return out(
match &c[2] {
"on" => (a / b - 1.0) * 100.0,
"off" => (1.0 - a / b) * 100.0,
_ => a / b * 100.0,
},
"%",
);
}
if let Some(c) = re!(r"^what\s*% is (.+) of (.+)$").captures(&s) {
return out(val(&c[1])? / val(&c[2])? * 100.0, "%");
}
let s = re!(r"^(?:what % change is|% (?:change|increase|decrease) from) (.+) to (.+)$")
.replace(&s, "$1 to $2 is what %");
if let Some(c) = re!(r"^(.+) to (.+) (?:is what|as(?: a)?)\s*%$").captures(&s) {
if val(&c[1])? == 0.0 {
return Some(Err(crate::Error("null_result".into())));
}
return out((val(&c[2])? / val(&c[1])? - 1.0) * 100.0, "%");
}
if let Some(c) = re!(r"^(.+) is to (.+) as (what|.+) is to (what|.+)$").captures(&s) {
let (a, b) = (val(&c[1])?, val(&c[2])?);
return if &c[3] == "what" {
out(a / b * val(&c[4])?, "")
} else if &c[4] == "what" {
out(b / a * val(&c[3])?, "")
} else {
None
};
}
if let Some(c) = re!(r"^(.+?)\s*% (of|on|off|from) (.+)$").captures(&s) {
let (p, tail) = (val(&c[1])? / 100.0, c[3].trim());
if tail == "-0" {
return None;
}
let mut suffix = "";
let mut prefix = "";
let value = if let Some(v) = tail.strip_suffix('%') {
suffix = "%";
val(v)?
} else if let Some(v) = tail.strip_prefix('$') {
prefix = "$";
val(v)?
} else if let Some(v) = tail.strip_suffix(" kg") {
suffix = " kg";
val(v)?
} else {
val(tail)?
};
let mut n = match &c[2] {
"on" => value * (1.0 + p),
"off" => value * (1.0 - p),
_ => value * p,
};
if let Some((left, right)) = c[1].rsplit_once('/') {
n = val(left)? / (val(right)? / 100.0 * value);
}
if prefix == "$" && n.is_finite() {
return Some(Ok(super::money(n, "AUD")));
}
return out(n, suffix);
}
if s != input.to_lowercase() {
return eval(&s).and_then(|n| out(n, ""));
}
None
}
}