www.pdelong.com

Source for https://www.pdelong.com

git clone https://code.pdelong.com/www.pdelong.com.git

 1const form = document.getElementById("form");
 2const results = document.getElementById("results");
 3
 4const plates = [45, 35, 25, 10, 5, 2.5];
 5
 6function calculateWeights(weight) {
 7  var neededWeights = new Array();
 8
 9  if (weight < 45) {
10    throw new Error("Weight is less than the bar");
11  }
12
13  weight -= 45;
14  weight /= 2;
15
16  for (const plate of plates) {
17    if (weight == 0) {
18      break;
19    }
20
21    var needed = Math.floor(weight / plate);
22    if (needed > 0) {
23      neededWeights.push({ plate: plate, num: needed });
24      weight -= needed * plate;
25    }
26  }
27
28  if (weight == 0) {
29    return neededWeights;
30  } else {
31    throw new Error("That weight is impossible with normal plates");
32  }
33}
34
35function makePlateCount(weight, num) {
36  li = document.createElement("li");
37
38  span = document.createElement("span");
39  span.append("" + weight + " x " + num);
40  li.append(span);
41
42  return li;
43}
44
45form.addEventListener("submit", (event) => {
46  event.preventDefault();
47
48  while (results.firstChild) {
49    results.removeChild(results.firstChild);
50  }
51
52  var userWeight = document.getElementById("weight");
53  var weight =
54    userWeight.value === undefined || userWeight.value === ""
55      ? 0
56      : userWeight.value;
57
58  try {
59    var weights = calculateWeights(weight);
60
61    ul = document.createElement("ul");
62    for (const item of weights) {
63      ul.append(makePlateCount(item.plate, item.num));
64    }
65    results.append(ul);
66  } catch (error) {
67    warning = document.createElement("p");
68    warning.classList.add("warning");
69    warning.append(error.message);
70    results.append(warning);
71  }
72
73  return false;
74});