I am making a logic gate simulator and am struggling with the passing of values from one logic gate to another. I am not good at java script (or programming) and chat bots are not much help. I assume it is how the values are evaluated/parse from the initial coding blocks but not sure what to do to fix it.
here is the code: https://codepen.io/SEXYSEXY/pen/YzmjqWy
function evaluateCircuit() {
const values = {};
// Set initial input values
document.querySelectorAll('.input').forEach(input => {
const value = parseInt(input.dataset.value, 10);
if (value !== undefined) {
values[input.dataset.id] = value;
} else {
console.warn(`Input ${input.dataset.id} has no defined value.`);
}
});
connections.forEach(conn => {
const startId = conn.start.parentElement.dataset.id;
const endId = conn.end.parentElement.dataset.id;
if (!values[endId]) values[endId] = [];
values[endId].push(values[startId]);
});
console.log('Connections:', connections);
console.log('Initial Values:', values);
document.querySelectorAll('.gate').forEach(gate => {
const gateId = gate.dataset.id;
const gateType = gate.dataset.type;
let inputValues = values[gateId] || [];
// Ensure inputValues is an array
if (!Array.isArray(inputValues)) {
inputValues = [inputValues];
}
console.log(`Evaluating gate ${gateId} of type ${gateType} with inputs:`, inputValues);
let outputValue;
switch (gateType) {
case 'AND':
outputValue = inputValues.reduce((a, b) => (a !== undefined && b !== undefined) ? a & b : 0, 1);
break;
case 'OR':
outputValue = inputValues.reduce((a, b) => (a !== undefined && b !== undefined) ? a | b : 0, 0);
break;
case 'NOT':
outputValue = inputValues.length ? 1 - inputValues[0] : 0;
break;
case 'NAND':
outputValue = 1 - (inputValues.reduce((a, b) => (a !== undefined && b !== undefined) ? a & b : 0, 1));
break;
case 'NOR':
outputValue = 1 - (inputValues.reduce((a, b) => (a !== undefined && b !== undefined) ? a | b : 0, 0));
break;
case 'XOR':
outputValue = inputValues.reduce((a, b) => (a !== undefined && b !== undefined) ? a ^ b : 0, 0);
break;
case 'XNOR':
outputValue = 1 - inputValues.reduce((a, b) => (a !== undefined && b !== undefined) ? a ^ b : 0, 0);
break;
default:
outputValue = 0;
}
console.log(`Output of gate ${gateId} (${gateType}):`, outputValue);
values[gateId] = [outputValue]; // Store output value for the gate
});
document.querySelectorAll('.output').forEach(output => {
const outputId = output.dataset.id;
const outputValue = values[outputId] ? values[outputId][0] : 0;
console.log(`Output ${outputId}: ${outputValue}`);
});
}