How is the NAND gate implemented? (Conceptually) - javascript

I am trying to find the lowest level of things that you just can't implement because they are too low level. So it seems that all computation can be constructed from the NAND gate.
From the truth table it is easy to "implement" in JavaScript:
function nand(a, b) {
if (a == 0 && b == 0) return 1
if (a == 0 && b == 1) return 1
if (a == 1 && b == 0) return 1
if (a == 1 && b == 1) return 0
}
But this is cheating. Because how are the IF statements implemented? I don't quite know how to represent that if-statement link in code since I'm not sure familiar with logic gates/circuits, but I am pretty sure the IF statement itself could be represented as a combination of NAND gates.
So then it's turtles all the way down! A NAND gate is implemented with more NAND gates (for the if-statements), etc..
So how do we avoid this situation? Do we simply say that a NAND gate is an axiom? I am wondering because I'm wondering where the foundation for formal verification lies.
Put another way, the reason I'm asking is because I've noticed that every function can be implemented as other functions, even the IF statement and such. Everything can be implemented all the way down to NAND gates. But then I am left swinging, the NAND is a function too, but what is it's implementation?!? I'm confused/perplexed and need some guidance on how to think about this.

Since NAND is Not AND you can declare it using AND, which means that NAND is not an axiom:
function nand(a, b) {
return !(a && b)
}
console.log(nand(false, false)) // true
console.log(nand(true, false)) // true
console.log(nand(false, true)) // true
console.log(nand(true, true)) // false
Using multiplication you can declare NAND with 0 and 1. Since AND is a * b (you get 1 if both are 1), NAND is 1 - a * b:
function nand(a, b) {
return 1 - a * b
}
console.log(nand(0, 0)) // 1
console.log(nand(1, 0)) // 1
console.log(nand(0, 1)) // 1
console.log(nand(1, 1)) // 0

Related

Compering undefined, null and values

I want to run this in my code: if(a > b){ do something} where a and b can be sometimes undefined or null and sometimes comparable(e.g. both a number).
Is it ok in javascript to do this?
I only want the if to be true if they are comparable.
In general, you should never attempt to compare things of different types without defining your rules for how you want them to be compared. While there's actually a very strict set of rules defined in JS standard for comparing values of different types, you're opening the big can of worms if you try to design your code around this set.
What you might consider doing instead is separating type casting operation from comparison operation. For example:
function firstIsGreater(numA, numB) {
if (typeof numA !== 'number') return false;
if (typeof numB !== 'number') return false;
return numA > numB;
}
Strictly speaking, those checks are not required here. For example, when you compare with undefined, that gets cast to NaN, and any comparison involving NaN results in false.
The problem is that usually mixture of types is a sign of much bigger problems in your outlying code - and instead of returning false you might consider throwing errors, or at least triggering some warnings.
In general you should validate the values and cast them to the types you're completely aware of at the very moment those values arrive into your system from some external components - server-side calls, user input etc.
if(typeof a == 'number' && typeof b == 'number' && a > b){ do something}
This will only run "do something" if a and b are both numbers and a is greater than b.
Any undefined value in combination with a comparison of less than <, greater than > or less than or equal or graater than or equal yields false.
Any null value is converted to zero in an number like environment.
Maybe this table helps: Loose equality using ==
if (undefined < 3) console.log('undefined < 3');
if (undefined > 3) console.log('undefined > 3');
if (undefined <= 3) console.log('undefined <= 3');
if (undefined >= 3) console.log('undefined >= 3');
if (null < 3) console.log('null < 3');
if (null > 3) console.log('null > 3');
if (null <= 3) console.log('null <= 3');
if (null >= 3) console.log('null >= 3');

Performing xnor in javascript

I have two strings stored in a & b. I want to perfrom some validation if both strings have some value. For this I use:
if(a && b) {
//Do some processing.
}
However if one of them is empty and the other is not, then I need to treat it separately. If both are empty, I don't need to do anything. So basically to handle this case it is the false case of XNOR.
I could do this way:
if((a && !b) || (!a && b)) {
//handle separately.
}
Is there a better approach than this?
Let's combine your two separate if-statements into one (effectively the same, but will help with the simplification):
if (a && b)
// do some processing
else if (a && !b || !a && b)
// do other processing
To figure out if we can simplify further, let's look at the truth table for the second condition:
a | b | x
--------------
1 | 0 | 1 (a && !b)
0 | 1 | 1 (!a && b)
0 | 0 | 0 (a && b) (negating the first if)
You can see that the positive outcomes (x = 1) are present when a is true or when b is true, which simplifies to a || b. The final version of your if-statement would look like:
if (a && b)
// do some processing
else if (a || b)
// do other processing
JavaScript does not have XOR and XNOR operators. There are many ways to implement them, and the way you implemented it is fine. Another way can be by using the ternary operator:
//XOR
if( a ? !b : b ) {
...
}
//XNOR
if( a ? b : !b ) {
...
}
However, all those methods have a downside of potentially evaluating a and b more than once. That can be a problem if a or b is a function or expression. A better approach can be by rewording the definition of XOR to: return true if the two boolean operands do not have the same value. We can implement that like this:
//XOR
if( a != b ) {
...
}
//XNOR
if( a == b ) {
...
}
Now, this is much shorter and, more importantly, only evaluates a and b once. However, this only works if both a and b are booleans. If you want to support other types, you'll have to convert them to booleans first:
//XOR
if( !a != !b ) {
...
}
//XNOR
if( !a == !b ) {
...
}

Javascript usage of && operator instead of if condition

What's the point of having this logical operator like this: r == 0 && (r = i);?
function do()
{
var r = 0;
var i = 10;
r == 0 && (r = i);
}
is this the same as:
if (r==0)
{
r=i;
}
What always helps me is translating it to words
var r = 0;
var i = 10;
r == 0 && (r = i);
translates to
set variable r to zero
set variable i to ten
if variable r equals zero AND the return of the following statement "set variable r to value of variable i"
do nothing, but r is now 10.
so in short, let's forget about 1 and 2.
In javascript the execution flow in a boolean comparisan is to stop execution of if statement parameters if any part from the && fails.
An boolean comparisan will execute from left to right.
1 == 1 && 2 == 3 && (r = i)
it will pass 1 == 1 fail on 2 == 3 and never reach the assigment operation.
Basically it's a shorthand for:
if(r == 0) {
r = i;
}
Simple yes r == 0 && (r = i);is same as
if (r==0)
{
r=i;
}
Just tested the speed of the code and the && is little bit faster (almost negligible).
Coming to the actual question, I found the place of using && instead of if us literally short hand code of later. However I never use the code as it highly kill the readability of code reader.
As docs says
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value.
But what we are seeing here is an assignment to the a variable based on other. Of course the code works but I believe, this is just a mis usage of the convention.
It is the same, in terms of logic and control flow.
It is shortening lines of code (code golf) by (ab)using short-circuit behavior.
The StackExchange page for code golf is https://codegolf.stackexchange.com.
For even shorter code, you could use a logical OR as default operator.
r = r || i;
Or
r || (r = i);
I've been reading some of the answers here and I've come up with this summary.
Short Summary
Condition on r: Assign i to r, in case r is null:
r = r || i
Or
r || (r = i)
Condition on i: Assign i to r, in case i is not null:
i && (r = i)
Or
r = i || r
More Examples
a || (Do Something) // Means: if `a` is `null`
!a || (Do Something) // Means: if `a` is **not** `null`
a && (Do Something) // Means: if `a` is **not** `null`
!a && (Do Something) // Means: if `a` is `null`
It is indeed the same, and a technique often used by minifiers to collapse code. In this case, you can even use an ! in order to do the if as you are comparing without typecheck:
!r && (r = i);
Or use an || operator for this assignment:
r = r || i;
If you want to keep your code clear, use an if tho.
Consider you have something to print only when r=0 and i=10. then && will be use full like.
if(r==0 && i==10){
console.log('its good practice')
}
if we use seperate, like
if(r==0){
if(i==10){
console.log('its bad practice')
}
}
what will you do if you have lots of condition to check.? i suggest you to use first one.

(!n%2) is the same as (!n%2 == 0)?

I am trying to understand this code from Eloquent JavaScript:
function unless(test, then) {
if (!test) then();
}
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
}
repeat(3, function(n) {
unless(n % 2, function() {
console.log(n, "is even");
});
});
// → 0 is even
// → 2 is even
I get that it says, run the following code 3 times testing with 0,1,2:
if (!n%2) function(n) {
console.log(n, "is even");
});
What I don't get is how we get true/false from (!n%2)?
Is (!n%2) the same as (!n%2 == 0)?
Logical NOT ! has higher precedence than modulo operator %.
Thus, (!n%2) is equivalent to (!n) % 2 which will always return 0 a falsy value except when n = 0.
Whereas (!n%2 == 0) will return true(again except 0).
They both are not equal, in fact they are opposite of each other(falsy vs truthy value).
You need !(n % 2).
Or simply to check if number is even
n % 2 === 0
Your test code you wrote is not equivalent to the sample code from the article.
In the sample code, n % 2 is evaluated first, and the result is passed into the unless function. There, you are performing a Logical Not operation against the result.
If n is even, n % 2 will pass 0 to unless. A Boolean comparison of 0 returns false, and the ! negates the result (logical not), so !0 == true. this, in turn, causes the then function to fire.
If n is odd, the opposite occurs. Some value other than 0 is passed, which evaluates to false, causing then to not fire.
In contrast, your attempt to reproduce the sample code without using Higher-Order functions won't work the same way. !n % 2 will perform the Logical Not on n first, then try to modulo the result. !(n % 2) is a better representation of the sample code.
!Boolean(n%2) should work as a way to determine whether one is even or odd.
Remember that Boolean does not follow BIDMAS.
It does !n first where n is treated as a Boolean so that the numerical value of 0 is treated as false and any other numerical value is treated as true. The exclamation mark inverts the logic state of n.
Now the %2 converts the Boolean back to an integer where true is 1 and 0 is false. !n = 0 returns 0 and !n = 1 returns 1.
Using !n%2 in an if statement converts it back to a Boolean (1 = true, 0 = false).
Thus if n = 0 then the if statements proceeds because it returned true. If n != 0 (!= meaning not equal) then if statement is skipped because it returned false.
No, it's not. As stated here the "!" operator has highest precedence than "%" so the expression will return true if n is 0 and false if n is different from 0.
More in detail, suppose n is 2. the execution of the expression is:
(!n)%2
(!2)%2
0%2
0
so it is false, now for n=0
(!0)%2
1%2
1
so it is true. It is the opposite behavior of (!n%2 == 0) that returns true if n is different from 0 and false otherwise since == has less precendence and the comparison with 0 is executed at the end of the calculation above. You can easily convince yourself by using this simple javascript with different values of n:
n = 1;
if(!n%2)
{
document.getElementById("par1").innerHTML="true";
}
if(!n%2 == 0)
{
document.getElementById("par2").innerHTML="true";
}

Which operator is the fastest in Javascript to check whether 2 values are equal to 0?

Which of the following is fastest and what is the justification for why?
(1) if (x == 0 and y == 0)
(2) if ((x | y) == 0)
(3) Other (Please mention. If any)
I would probably use Strict Equality if you want to check they are exactly the same, ie they're the same type too, just in case.
if (x=== 0 && y === 0)

Categories

Resources