summaryrefslogtreecommitdiff
path: root/static/script.js
blob: ced777cf0399a1b88f3f03c49fcf78dba4551083 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"use strict";

var html = ``
for (var table in data) {
    var s = ``
    for (var idx in data[table]) {
        let tag = table + '|' + idx
        s += `<input type="checkbox" id="ingredient${tag}" x-ingredient="${tag}">
            <label for="ingredient${tag}">${data[table][idx].name}</label>`
    }
    html += `<fieldset><legend>${table}</legend>${s}</fieldset>`
}
html += `<fieldset><legend>Dressing amount</legend>
        <input type="radio" name="dressing-amount" id="light" value="light">
        <label for="light">Light</label><br>
        <input type="radio" name="dressing-amount" id="medium" value="medium">
        <label for="medium">Medium</label><br>
        <input type="radio" name="dressing-amount" id="heavy" value="heavy">
        <label for="heavy">Heavy</label><br>
    </fieldset>`

nutrition = document.getElementById('nutrition')
form = document.getElementById('form')
form.innerHTML = html

let multipliers = {'none': 0, 'light': 1, 'medium': 2, 'heavy': 3}

function calculateNutrition() {
    let total = {}
    let dressingAmount = form.elements['dressing-amount'].value || 'none'
    for (var el of document.querySelectorAll('input:checked')) {
        if (el.getAttribute('type') == 'radio') {
            continue
        }
        let tag = el.getAttribute('x-ingredient')
        let table = tag.split('|')[0]
        let idx = tag.split('|')[1]
        let row = data[table][idx]
        for (var [name, val] of Object.entries(row)) {
            if (typeof val == 'string') {
                continue
            }
            if (!total[name]) {
                total[name] = 0
            }
            let multiplier = 1
            if (table == 'Dressings') {
                multiplier = multipliers[dressingAmount]
            }
            if (multiplier > 0) {
                total[name] += multiplier*val
            }
        }
    }
    return total
}

form.addEventListener('change', function() {
    let total = calculateNutrition()
    var s = `
        Calories: ${total.calories}<br>
        Carbohydrates (g): ${total.total_carbs}<br>
        Dietary fiber (g): ${total.dietary_fiber}<br>
        Fat (g): ${total.total_fat}<br>
        Protein (g): ${total.protein}<br>
    `
    nutrition.innerHTML = s
})