Last active
February 21, 2024 11:53
-
-
Save shawndumas/446aa4f79b8ec0b34bf1 to your computer and use it in GitHub Desktop.
Logic Gates (es6 version)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const logicGates = { | |
nand(a, b) { | |
return !(a && b); | |
}, | |
not(a) { | |
return this.nand(a, a); | |
}, | |
and(a, b) { | |
return this.not(this.nand(a, b)); | |
}, | |
or(a, b) { | |
return this.nand(this.not(a), this.not(b)); | |
}, | |
nor(a, b) { | |
return this.not(this.or(a, b)); | |
}, | |
xor(a, b) { | |
return this.and(this.nand(a, b), this.or(a, b)); | |
}, | |
xnor(a, b) { | |
return this.not(this.xor(a, b)); | |
} | |
}; | |
const results = Object.keys(logicGates) | |
.map(gate => [ | |
{ a: false, b: false }, | |
{ a: false, b: true }, | |
{ a: true, b: false }, | |
{ a: true, b: true }, | |
].map(test => { | |
const result = (({ a, b }) => logicGates[gate](a, b))(test); | |
const desc = JSON.stringify(test) | |
.replace(/:|"|\{|\}/g, ' ') | |
.replace(/\s+/g, ' ') | |
.replace(/true/g, 'true '); | |
return `${gate}:${desc}= ${result}\n`; | |
}).join('') | |
).join('\n'); | |
console.log(results); | |
/* | |
nand: a false, b false = true | |
nand: a false, b true = true | |
nand: a true , b false = true | |
nand: a true , b true = false | |
not: a false, b false = true | |
not: a false, b true = true | |
not: a true , b false = false | |
not: a true , b true = false | |
and: a false, b false = false | |
and: a false, b true = false | |
and: a true , b false = false | |
and: a true , b true = true | |
or: a false, b false = false | |
or: a false, b true = true | |
or: a true , b false = true | |
or: a true , b true = true | |
nor: a false, b false = true | |
nor: a false, b true = false | |
nor: a true , b false = false | |
nor: a true , b true = false | |
xor: a false, b false = false | |
xor: a false, b true = true | |
xor: a true , b false = true | |
xor: a true , b true = false | |
xnor: a false, b false = true | |
xnor: a false, b true = false | |
xnor: a true , b false = false | |
xnor: a true , b true = true | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment