const imperialUnitNames = ["cup", "ounce", "teaspoon", "pound"]; function findImperialUnitIndex(text) { return imperialUnitNames.findIndex(unitName => text.includes(unitName)) } function textToNumber(text) { if (text == "¼") { return 0.25 } else if (text == "½") { return 0.5 } else if (text.includes("/")) { const [beforeSlash, afterSlash] = text.split("/") return Number(beforeSlash) / Number(afterSlash) } else { return Number(text) } } function convertUnits(amount, unitName) { if (unitName.includes("cup")) { amount = textToNumber(amount) const mlAmount = Math.round(amount*236.5882365) const gramsAmount = Math.round(amount*201.6) return ["~" + mlAmount, "ml or (~" + gramsAmount + " g)" ] } else if (unitName.includes("teaspoon")) { amount = textToNumber(amount) const mlAmount = Math.round(amount*5.919388) const gramsAmount = Math.round(amount*4.2605668424239) return ["~" + mlAmount, "ml or (~" + gramsAmount + " g)" ] } else if (unitName.includes("pound")) { return ["~" + Math.round(amount*453.59237), "grams"] } else if (unitName.includes("ounce")) { //amount = textToNumber(amount) //const gramsAmount = Math.fround(amount * 28.34952); return [amount, unitName] //return ["~" + , "grams"] } else { return [amount, unitName] } } function textNodesUnder(node) { var n, a=[], walk=document.createTreeWalker(node,NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,null,false) while(n=walk.nextNode()) a.push(n) return a } function replaceImperialUnitsInText(text) { const words = text.split(" ") for (let i = 1; i < words.length; i++) { if (findImperialUnitIndex(words[i]) != -1) { const [newAmount, newUnitName] = convertUnits(words[i-1], words[i]); words[i-1] = newAmount words[i] = newUnitName updated = true } } return words.join(" ") } const content = document.getElementsByClassName("loc article-content")[0] for (const textNode of textNodesUnder(content)) { if (!textNode.parentElement) continue; if (textNode.parentElement.classList.contains("mntl-structured-ingredients__list-item")) { let quantityChild; let unitNameChild; for (const child of textNode.childNodes) { if (!child.dataset) continue if ("ingredientQuantity" in child.dataset) { quantityChild = child } else if ("ingredientUnit" in child.dataset) { unitNameChild = child } } if (unitNameChild && quantityChild && quantityChild.textContent.length > 0) { if (findImperialUnitIndex(unitNameChild.textContent) == 0) { const [newAmount, newUnitName] = convertUnits(quantityChild.textContent, unitNameChild.textContent); quantityChild.textContent = newAmount unitNameChild.textContent = newUnitName } else { } } } else if (textNode.nodeValue && findImperialUnitIndex(textNode.nodeValue) != -1) { textNode.nodeValue = replaceImperialUnitsInText(textNode.nodeValue) } }