Add diffing algorithm

This commit is contained in:
SkyfallWasTaken 2024-07-01 18:16:14 +01:00
parent 4aad2a3228
commit 3d7a3a9d44
3 changed files with 70 additions and 1 deletions

68
src/diff.rs Normal file
View file

@ -0,0 +1,68 @@
use crate::items::ShopItem;
pub fn diff_items(old: ShopItem, new: ShopItem) -> Option<String> {
if old == new {
// The items are the exact same
return None;
}
let mut result = Vec::new();
result.push("*Item updated*".into());
if old.full_name != new.full_name {
result.push(format!("*Name:* {}{}", old.full_name, new.full_name));
} else {
result.push(format!("*Name:* {}", new.full_name));
}
if old.description != new.description {
result.push(format!(
"*Description:* {} → {}",
old.description.unwrap_or("_not set_".into()),
new.description.unwrap_or("_not set_".into())
));
}
if old.price != new.price {
result.push(format!("*Price:* {}{}", old.price, new.price));
}
if old.stock != new.stock {
result.push(format!(
"*Stock:* {} → {}",
old.stock
.map(|stock| stock.to_string())
.unwrap_or("Unlimited".into()),
new.stock
.map(|stock| stock.to_string())
.unwrap_or("Unlimited".into())
));
}
Some(result.join("\n"))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn price_diff() {
let old = ShopItem {
full_name: "Test".into(),
price: 1,
..Default::default()
};
let new = ShopItem {
full_name: "Test".into(),
price: 2,
..Default::default()
};
assert_eq!(
diff_items(old, new),
Some("*Item updated*\n*Name:* Test\n*Price:* 1 → 2".into())
);
}
}

View file

@ -2,7 +2,7 @@ use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use worker::*;
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ShopItem {
#[serde(rename = "Full Name")]
pub full_name: String,

View file

@ -1,5 +1,6 @@
use worker::*;
mod diff;
mod items;
#[event(fetch, respond_with_errors)]