To update the function to handle both millilitres and litres in addition to grams and kilograms, and display the label /100ml or /100g accordingly, you can modify the code as follows. I've added the necessary changes and patterns to handle volumes (millilitres and litres) and added a function to determine the correct unit and calculate the price per 100 units accordingly.
function calculatePricePer100Units(price, units, isVolume) {
const pricePer100Units = (parseFloat(price) / parseFloat(units)) * 100;
return pricePer100Units.toFixed(2) + (isVolume ? '/100ml' : '/100g');
}
const GRAMS_PATTERN = /(\d+)\s*g/i;
const KILOGRAMS_PATTERN = /(\d+)\s*kg/i;
const MILLILITRES_PATTERN = /(\d+)\s*ml/i;
const LITRES_PATTERN = /(\d+)\s*l/i;
function extractUnitsFromTitle(title) {
let match = title.match(GRAMS_PATTERN);
let isVolume = false;
if (!match) {
match = title.match(KILOGRAMS_PATTERN);
if (!match) {
match = title.match(MILLILITRES_PATTERN);
isVolume = true;
if (!match) {
match = title.match(LITRES_PATTERN);
isVolume = true;
if (!match) return { units: null, isVolume: false };
const parsed = parseInt(match[1]) * 1000;
if (isNaN(parsed)) return { units: null, isVolume: false };
return { units: parsed, isVolume };
}
}
}
const parsed = parseInt(match[1]) * (isVolume && match[0].toLowerCase().includes('l') ? 1000 : 1);
if (isNaN(parsed)) return { units: null, isVolume: false };
return { units: parsed, isVolume };
}
function addPrices() {
const menuItems = document.querySelectorAll("#main-content ul li");
for (const menuItem of menuItems) {
const candidates = menuItem.querySelectorAll(
'div > span[data-testid="rich-text"]'
);
let title;
let price;
let priceElement;
for (const item of candidates) {
const textContent = item.textContent.trim();
if (!textContent) continue;
if (textContent.includes("$") && !textContent.includes("/100g") && !textContent.includes("/100ml")) {
const computedStyle = window.getComputedStyle(item);
if (computedStyle.textDecorationLine === "line-through") continue;
price = textContent.replace("$", "");
priceElement = item;
} else if ((textContent.includes("g") || textContent.includes("l")) && textContent.includes(" ")) {
title = textContent;
}
}
if (!title || !price || !priceElement) continue;
const { units, isVolume } = extractUnitsFromTitle(title);
if (!units) continue;
const pricePer100Units = calculatePricePer100Units(price, units, isVolume);
const pricePer100UnitsElement = document.createElement("span");
pricePer100UnitsElement.textContent = ` - $${pricePer100Units}`;
pricePer100UnitsElement.style.color = "#7f7f7f";
pricePer100UnitsElement.style.fontSize = "0.75rem";
priceElement.appendChild(pricePer100UnitsElement);
}
}
setInterval(addPrices, 250);
This updated script includes handling for both volume (millilitres and litres) and weight (grams and kilograms), determining the correct unit based on the title, and appending the appropriate label ( or ) next to the price.