Last active
February 21, 2024 11:53
-
-
Save shawndumas/b93363b11362207e4443 to your computer and use it in GitHub Desktop.
Tagged Template
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)); } | |
}; | |
// 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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment