I'm trying to create a function that calculates how many 6-meter bars I need for different pieces of different sizes. For example, if I need 3 pieces, each 4 meters long, I obviously need 3 bars, but I can't seem to create a function that does that. Please help.
I tried to create a list and have another function count the leftovers of the iteration based on the input value, but I didn't succeed.
let trozos = [];
/*add number of pieces*/
function agregarTrozos() {
const numTrozos = parseInt(document.getElementById("trozos").value);
const tamanoTrozo = parseFloat(document.getElementById("tamano").value);
if (!isNaN(numTrozos) && !isNaN(tamanoTrozo)) {
for (let i = 0; i < numTrozos; i++) {
trozos.push(tamanoTrozo);
actualizarListaTrozos();
}
document.getElementById("trozos").value = "";
document.getElementById("tamano").value = "";
}
}
/*update number of chunks*/
function actualizarListaTrozos() {
const listaTrozos = document.getElementById("listaTrozos");
listaTrozos.innerHTML = "";
trozos.forEach(tamano => {
const li = document.createElement("li");
li.textContent = tamano + " meters";
listaTrozos.appendChild(li);
});
}
/*calculation of necessary bars*/
function calcularBarras() {
const longitudBarra = 6;
let longitudTotal = trozos.reduce((total, tamano) => total + tamano, 0);
let barrasNecesarias = 0;
while (longitudTotal > 0) {
barrasNecesarias++;
longitudTotal -= longitudBarra;
}
document.getElementById("resultado").textContent = barrasNecesarias;
}
/* clean */
function limpiar() {
trozos = [];
actualizarListaTrozos();
document.getElementById("resultado").textContent = "";
}
<div id="container">
<h1>Bar Calculator</h1>
<p>Each bar measures 6</p>
<label for="trozos">Number of Pieces:</label>
<input type="number" id="trozos">
<label for="tamano">Piece Size (meters):</label>
<input type="number" id="tamano">
<button onclick="agregarTrozos()">Add</button>
<hr>
<h2>Metal Pieces</h2>
<ul id="listaTrozos"></ul>
<hr>
<button onclick="calcularBarras()">Calculate Necessary Bars</button>
<h2>Necessary Bars: <span id="resultado"></span></h2>
<button onclick="limpiar()">Clean</button>