Bugdetbytes american to international unit converter

Convert freedom units to international units

As of 2018-11-21. See the latest version.

// ==UserScript==
// @name         Bugdetbytes american to international unit converter
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Convert freedom units to international units
// @author       Histidin
// @match        https://www.budgetbytes.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Convert fractions x/y into floating point numbers
    function numberize(number) {
        if(number.includes("/")) {
            var division = []
            division = number.split("/")
            number = parseFloat(division[0]) / parseFloat(division[1])
        }
        else {
            parseFloat(number)
        }
        return number
    }
    
    // Unit converter
    function FreedomToSI(amount, unit) {
        // normal units
        switch(unit) {
            case "cup":
                amount = amount*236.588
                unit = "ml"
                break;
            case "cups":
                amount = amount*236.588
                unit = "ml"
                break;
            case "lb":
                amount = amount*453.592
                unit = "g"
                break;
            case "lb.":
                amount = amount*453.592
                unit = "g"
                break;
            case "oz.":
                amount = amount*28.3495
                unit = "g"
                break;
            case "oz":
                amount = amount*28.3495
                unit = "g"
                break;
            case "oz. block":
                amount = amount*28.3495
                unit = "g"
                break;
        }
        // Converts oz. cans to g cans
        var regex = /(\d+)oz\. can/
        if(unit.match(regex)) {
            var cansize = unit.match(regex);
            var canSI = FreedomToSI(cansize[1], "oz")
            unit = canSI[0]+"g can"
        }
        // Round number above threshold. Threshold is necessary to avoid 0 when amount is small
        if(amount > 20) {
            amount = Math.round(amount)
        }
        return([amount,unit])
    }

    var rootnode=document.getElementsByClassName("wprm-recipe-ingredient")

    var i = 0
    for(i = 0; i < rootnode.length; i++) {
        var node = rootnode[i]
        if(node.childElementCount == 4) {
            var SIamount = [];
            var amount = node.children[0].textContent
            var unit = node.children[1].textContent
            amount = numberize(amount)
            SIamount = FreedomToSI(amount, unit)
            node.children[0].textContent = SIamount[0]
            node.children[1].textContent = SIamount[1]
        }
    }
})();