Skip to content

Instantly share code, notes, and snippets.

@ianstarz
Forked from shawndumas/taggedTemplate.js
Last active April 17, 2022 03:34
Show Gist options
  • Save ianstarz/bed8fcbb3ede329dc2e0 to your computer and use it in GitHub Desktop.
Save ianstarz/bed8fcbb3ede329dc2e0 to your computer and use it in GitHub Desktop.
Build up all the logic gates from nand in js
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)); }
};
// it would be better/easier to just make prettyPrintTest a function
// that got invoked in the template but I wanted to mess around
// with tagged templates.
const prettyPrintTest = (...args) => args.shift().slice()
.map((str, i) => {
let arg = (args[i] === undefined ? '' : args[i]);
if (typeof arg === 'object') {
arg = JSON.stringify(arg)
.replace(/:|"|\{|\}/g, ' ')
.replace(/\s+/g, ' ')
.replace(/true/g, 'true ')
}
return str + arg;
}).join('');
const tests = Object.keys(logicGates)
.map(gate => [
{ a: false, b: false },
{ a: false, b: true },
{ a: true, b: false },
{ a: true, b: true },
].map(test => prettyPrintTest
`${gate}:${test}= ${(({ a, b }) => logicGates[gate](a, b))(test)}\n`)
.join('')
).join('\n');
console.log(tests);
/*
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
*/
@mathcat4
Copy link

Nice one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment