aboutsummaryrefslogtreecommitdiff
path: root/public/main.js
blob: b79f2b6fa8d915ac91d5d616d8ed70451b93117f (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
69
70
71
72
window.onload = function() {

  // Update ingredients amounts

  let inputs = []
  document.querySelectorAll('code').forEach(function (number) {

    // Install input
    const value = parseNumber(number.innerHTML)
    number.innerHTML = `<input value="${formatNumber(1, value)}">`

    // Push to inputs
    const element = number.children[0]
    inputs.push({ element, value })

    element.addEventListener('input', function() {

      // Parse modified input value
      const n = parseNumber(element.value)

      if (!isNaN(n)) {
        // Find current factor
        const currentInput = inputs.find(function (input) {
          return input.element === element
        })
        const factor = n / currentInput.value

        // Apply factor to other inputs
        inputs.forEach(function (input) {
          if (input.element !== currentInput.element) {
            input.element.value = formatNumber(factor, input.value)
          }
        })
      }
    })
  })

  // Set up done marks for steps

  document.querySelectorAll('ol > li').forEach(function (item) {
    item.addEventListener('click', function() {
      item.className = item.className ? '' : 'completed'
    })
  })

}

function parseNumber(value) {
  return parseFloat(value.replace(',', '.')) || 0
}

function formatNumber(factor, value) {
  if (factor === 1) {
    return value.toString().split('.').join(',')
  } else {
    const n = factor * value
    const xs = n.toString().split('.')
    const p = precision(value) || 1
    if (xs.length == 2) {
      return `${xs[0]},${xs[1].slice(0, p)}`
    } else {
      return n
    }
  }
}

function precision(value) {
  const xs = value.toString().split('.')
  if (xs.length === 2) {
    return xs[1].length
  }
}