use crate::{Context, Error, Outcome, Plugin, re};
use chrono::Datelike;
use std::collections::BTreeMap;
pub struct Inflation {
pub index: BTreeMap<i32, f64>,
}
impl Default for Inflation {
fn default() -> Self {
Self {
index: include_str!("../../data/price-index.csv")
.lines()
.skip(1)
.filter_map(|s| {
let (y, v) = s.split_once(',')?;
Some((y.parse().ok()?, v.parse().ok()?))
})
.collect(),
}
}
}
impl Inflation {
pub fn new(index: BTreeMap<i32, f64>) -> Self {
Self { index }
}
fn value(&self, year: i32) -> Option<f64> {
self.index.range(..=year).next_back().map(|(_, v)| *v)
}
}
impl Plugin for Inflation {
fn evaluate(&self, input: &str, ctx: &Context) -> Outcome {
let s = input.to_lowercase();
let today = ctx.now.with_timezone(&ctx.timezone).year().to_string();
let s = re!(r"^(.+) from today in (.+)$").replace(&s, "$1 today in $2");
if re!(r" is what \d{4}$").is_match(&s) {
return None;
}
let c = re!(r"^(.+) (?:from|in) (.+?) (?:(?:is |was )?(?:worth )?what (?:in )?)(.+)$")
.captures(&s)
.map(|c| (c[1].to_string(), c[2].to_string(), c[3].to_string()))
.or_else(|| {
re!(r"^what (?:is|was) (.+) (?:from|in) (.+?) worth in (.+)$")
.captures(&s)
.map(|c| (c[1].to_string(), c[2].to_string(), c[3].to_string()))
})
.or_else(|| {
re!(r"^(?:what (?:is|was) |value of )(.+?) (?:worth )?in (.+)$")
.captures(&s)
.map(|c| (c[1].to_string(), today.clone(), c[2].to_string()))
})
.or_else(|| {
re!(r"^(.+) (?:was|is) worth what in (.+)$")
.captures(&s)
.map(|c| (c[1].to_string(), today.clone(), c[2].to_string()))
})
.or_else(|| {
re!(r"^(.+) (?:from )?today in (.+)$")
.captures(&s)
.map(|c| (c[1].to_string(), today.clone(), c[2].to_string()))
})
.or_else(|| {
re!(r"^(?:what is |value of )(.+) from (.+)$")
.captures(&s)
.map(|c| (c[1].to_string(), c[2].to_string(), today.clone()))
})
.or_else(|| {
re!(r"^(.+) in (.+) dollars$")
.captures(&s)
.map(|c| (c[1].to_string(), c[2].to_string(), today.clone()))
})
.or_else(|| {
re!(r"^(.+) in (.+) today$")
.captures(&s)
.map(|c| (c[1].to_string(), c[2].to_string(), today.clone()))
})?;
let year = |s: &str| {
s.parse::<i32>()
.ok()
.or_else(|| super::calendar::date(s, ctx).map(|d| d.year()))
};
let (a, b) = (year(&c.1)?, year(&c.2)?);
let (value, code) = super::finance::amount(&c.0)?;
let (Some(a), Some(b)) = (self.value(a), self.value(b)) else {
return Some(Err(Error("null_result".into())));
};
super::finance::render(value * b / a, code)
}
}