Created
          October 8, 2023 17:55 
        
      - 
      
 - 
        
Save tripdragon/6205e26cf8cf83335de76d3eb756e4af to your computer and use it in GitHub Desktop.  
    javascript logic gates
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | // simple good readable source | |
| // https://www.codeproject.com/Articles/237465/Understanding-Logic-Gates | |
| // docs | |
| // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND | |
| // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators | |
| const lgates = { | |
| // AND : true when both inputs are true | |
| and : (a,b) => {return a & b}, | |
| // OR : true when both inputs are false | |
| or : (a,b) => {return a | b}, | |
| // XOR : true when one input is true and the other is false | |
| xor : (a,b) => {return a ^ b}, | |
| // NOT : reverse of input true = false , false = true | |
| not : (a) => { | |
| if (~a === -1) { | |
| return 1; | |
| } | |
| return 0; | |
| }, | |
| // NAND : is AND inverted, true when not all are true | |
| nand : (a,b) => {return 1 - a * b}, | |
| // NOR : is OR inverted, true when no inputs are true | |
| nor : (a,b) => { | |
| let g = ~ (a | b); | |
| if (g == -1) { | |
| return 1; | |
| } | |
| return 0; | |
| }, | |
| // XNOR : is XOR inverted, true when both inputs are same | |
| xnor : (a,b) => { | |
| if(a == b){ | |
| return 1; | |
| } | |
| return 0; | |
| } | |
| } | |
| console.log(lgates.and(0,0)); // false | |
| console.log(lgates.and(1,0)); // false | |
| console.log(lgates.and(0,1)); // false | |
| console.log(lgates.and(1,1)); // true | |
| console.log(lgates.or(0,0)); // false | |
| console.log(lgates.or(0,1)); // true | |
| console.log(lgates.or(1,0)); // true | |
| console.log(lgates.or(1,1)); // true | |
| console.log(lgates.xor(0,0)); // false | |
| console.log(lgates.xor(1,0)); // true | |
| console.log(lgates.xor(0,1)); // true | |
| console.log(lgates.xor(1,1)); // false | |
| console.log(lgates.not(0)); // true | |
| console.log(lgates.not(1)); // false | |
| console.log(lgates.nand(0,0)); // true | |
| console.log(lgates.nand(1,0)); // true | |
| console.log(lgates.nand(0,1)); // true | |
| console.log(lgates.nand(1,1)); // false | |
| console.log(lgates.nor(0,0)); // true | |
| console.log(lgates.nor(1,0)); // false | |
| console.log(lgates.nor(0,1)); // false | |
| console.log(lgates.nor(1,1)); // false | |
| console.log(lgates.xnor(0,0)); // true | |
| console.log(lgates.xnor(1,0)); // false | |
| console.log(lgates.xnor(0,1)); // false | |
| console.log(lgates.xnor(1,1)); // true | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment