Reputation: 31
I am building a computer simulation in which the user can create complex logic gates using building blocks like AND, OR, NOT and I would like the program to store the structure of the logic gate in a new function.
For example, XOR is a complex logic operation that looks like this in my function notation
AND( OR(x1, x2), NOT(AND(x1, x2)) )
where x1 and x2 are two boolean inputs. How can I generate a function like XOR(x1, x2) and be able to call it whenever I want. I don't want it hard coded in, I want to be able to generate it depending on what gates are being used and how they are connected.
Any ideas or thoughts or clarifying questions would be greatly appreciated!
xor returns true if one input is on but not if both are on.
Upvotes: 0
Views: 146
Reputation: 28196
Generally this is considered "unsafe", but it is certainly the most direct and intuitive answer: use eval()
:
const AND = (a,b) => a&&b;
const OR = (a,b) => a||b;
const NOT = a => !a;
const a=true; b=false;
eval("XOR=(a,b)=>AND(OR(a,b),NOT(AND(a,b)))");
console.log(XOR(a,b));
console.log(XOR(a,a));
console.log(XOR(b,a));
console.log(XOR(b,b));
This can of course be embedded in a function that carries out some preprocessing and "safety checks" before actually applying the eval()
-function on the user-supplied function-definition-string.
Upvotes: 1
Reputation: 7295
How about:
function XOR(var1, var2) {
return var1 !== var2;
}
Where var1
and var2
are booleans.
Or
function XOR(var1, var2) {
return AND( OR(var1, var2), NOT(AND(var1, var2)) );
}
Upvotes: 0