How to generate truth table by coding in Javascript for three literals (a, b, c) and also find a given boolean expression (![(a && b) || c])?
I am trying following code:
let input = ['a', 'b', 'c'];
let expression = ['(a&&b)', '((a&&b)||c)', '(!((a&&b)||c))'];
let tableValue = [];
function exp(input, expression) {
for (let i = 0; i <= Math.pow(2, input.length) - 1; i++) {
for (let j = 0; j <= input.length - 1; j++) {
if (('a&&b')) {
tableValue[j] = (i & Math.pow(2, j)) == false;
}
}
console.log(tableValue);
}
}
console.log(exp(input));
That
if (('a&&b'))doesn't evaluate anything. It's a string, not a function that you can call with the values. That's something you should use instead, e.g.Then you can fill your table by calling the function, like
Instead of logging, you can also build a table row values object (and format it later), and using your approach with bitwise operators you can do it for an arbitrarily large number of boolean variables:
You can also do this with dynamic expressions that are given as strings, if you insist, using a form of
eval: