isEven function wierd way [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 months ago.
Improve this question
I was playing around with on of the excercises when I coded this:
function isEven(x){
var m = x % 2
var n = x / 2
return m <= !n
}
The funny part is that it actually works, but I do not understand if !n makes the number negative or affects the boolean value itself. Can someone explain how my code works? Thanks.

!n is a red herring. For any value of x other than 0, !n will be false; it will be true when x == 0.
m is 0 for even numbers, 1 for odd numbers. When you compare a number with a boolean, the boolean is converted to a number. So m <= false is equivalent to m <= 0. This will be true when m is 0.
So you can get rid of n and just use this:
function isEven(x){
var m = x % 2;
return m <= false
}
[0, 1, 2, 3, 4, 5, 6, 7, 8].forEach(x => console.log(x, isEven(x)));
The reason why it works with !n is because in the only case where !n is true, x == 0 and m == 0. 0 <= true is true, so the function returns the correct result then as well.

First
var n = x / 2
n will be falsey if x is 0, and truthy otherwise.
If the argument is even and not 0:
m will be 0
n will be a truthy number (because anything divided by 2 is another non-zero number - except 0)
!n will be false (because that's the boolean inverse of 0, a falsey value)
the return statement is 0 <= false; false gets converted into a number when compared with <=, and 0 <= 0 is true
If the argument is odd and positive:
m will be 1
n will be truthy (because any odd number divided by 2 is another non-zero number, and a non-zero number is truthy)
!n will be false (because that's the boolean inverse of a truthy value)
the return statement is 1 <= false; false gets converted into a number when compared with <=, and 1 <= 0 is false
If the argument is even and 0:
m will be 0
n will be 0
!n will be true (boolean inverse of 0)
the return statement is 0 <= true; true gets converted into a number when compared with <=, and 0 <= 1 is true
But the code doesn't work when the argument is odd and negative, because a negative odd number % 2 gives -1, not 1.
m will be -1
n will be truthy (because any odd number divided by 2 is another non-zero number, and a non-zero number is truthy)
!n will be false (because that's the boolean inverse of a truthy value)
the return statement is -1 <= false; false gets converted into a number when compared with <=, and -1 <= 0 is true - when it should be false

Related

What is the best way to determine if a given number is a power of two?

Is there a more effective way to return true if n is a power of two or false if not?
function isPowerOfTwo(n) {
return Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
}
You can actually use ECMAScript5 Math.log:
function powerOfTwo(x) {
return (Math.log(x)/Math.log(2)) % 1 === 0;
}
Remember, in math, to get a logarithm with an arbitrary base, you can just divide log10 of the operand (x in this case) by log10 of the base. And then to see if the number is a regular integer (and not a floating point), just check if the remainder is 0 by using the modulus % operator.
In ECMAScript6 you can do something like this:
function powerOfTwo(x) {
return Math.log2(x) % 1 === 0;
}
See the MDN docs for Math.log2.
Source: Bit twiddling Hacks,
function powerOf2(v) {
return v && !(v & (v - 1));
}
You just bitwise AND the previous number with the current number. If the result is falsy, then it is a power of 2.
The explanation is in this answer.
Note:
This will not be 100% true for programming, mathematical, [also read 'interviewing']. Some edge cases not handled by this are decimals (0.1, 0.2, 0.8…) or zero values (0, 0.0, …)
Using bitwise operators, this is by far the best way in terms of efficiency and cleanliness of your code:
function PowerofTwo(n){
return ((x != 0) && !(x & (x - 1)));
}
what it does is checks the bits that make up the number, i.e. 8 looks like this:
1 0 0 0
x-1 or 7 in this case looks like this
0 1 1 1
when the bitwise operator & is used it invokes an && on each bit of the number (thus 1 & 1 = 1, 1 & 0 = 0, 0 & 1 = 0, 0 & 0 = 1):
1 0 0 0
-0 1 1 1
=========
0 0 0 0
since the number turns into an exact 0 (or false when evaluted as a boolean) using the ! flag will return the correct answer
if you were to do this with a number like 7 it would look like this:
0 1 1 1
-0 1 1 0
=========
1 1 1 0
returning a number greater than zero causing the ! flag to take over and give the correct answer.
A number is a power of 2 if and only if log base 2 of that number is whole. The function below computes whether or not that is true:
function powerOfTwo(n){
// Compute log base 2 of n using a quotient of natural logs
var log_n = Math.log(n)/Math.log(2);
// Round off any decimal component
var log_n_floor = Math.floor(log_n);
// The function returns true if and only if log_n is a whole number
return log_n - log_n_floor == 0;
}
Making use of ES6's Math.clz32(n) to count leading zeros of a 32-bit integer from 1 to 2³² - 1:
function isPowerOf2(n) {
return Math.clz32(n) < Math.clz32(n - 1);
}
/**
* #param {number} n
* #return {boolean}
*/
const isPowerOfTwo = function(n) {
if(n == 0) return false;
while(n % 2 == 0){
n = n/2
}
return n === 1
};
function PowerOfTwo(n){
// Exercise for reader: confirm that n is an integer
return (n !== 0) && (n & (n - 1)) === 0;
}
console.log(PowerOfTwo(3))
console.log(PowerOfTwo(4))
This is for a specific online course that requires an answer in a specific way.
Without using libraries and other methods just loops and .push.
you need to create an inner loop using while
it should start with 1
keep multiplying it with 2 until i,j,k or whatever is greater than the current number(array) so it will have to do 2 4 6 8 10 12 14 16 18 until it is greater than the number
then it will go to the outer loop then repeat again until
const numbers = [5, 3, 9, 30];
const smallestPowerOfTwo = arr => {
let results = new Array;
// The 'outer' for loop -
for (let i = 0; i < arr.length; i++) {
number = arr[i];
// The 'inner' while loop
j = 1;
while (j < number) { //starting from 1 then multiplied by 2 then by 2 again untill it is more than the number
j = j * 2;
}
results.push(j);
}
return results
}
console.log(smallestPowerOfTwo(numbers))

What does the zero refer to in the code below

I know this is a very basic question but what does the 0 refer to in the code below
var even = arr.filter(function(val) {
return 0 == val % 2;
});
what does the 0 refer to
Here 0 refers to the Number 0.
0 == val % 2
will evaluate to true or false which you are returning.
0 is the tested value of val modulus (%) 2. When there is no "remainder", as with even numbers, it will return the number 0. For odd numbers it will have a remainder of 1 and the function will return false to filter().
The % is the modulus operator, it works like this
The remainder operator (modulus) returns the first operand modulo the
second operand, that is, var1 modulo var2. The modulo function
is the integer remainder of dividing var1 by var2
MDN
In other words, if val can be divided by 2, the modulus operator returns 0 as there is no remainder, that's why it checks for a zero
Turning the yoda condition around, it makes more sense
val % 2 === 0; // can be divided by 2, so it's even, returns boolean
For instance if val was 4, 16, 200 etc, it would be true, as 4 can be evenly divided by 2.
If val was 3, 9, 201 etc. it would be false, as 3 can not be evenly divided by 2.
0 is just a number which is compared to right hand side expression val % 2
statement 0 == val % 2; returns true if val % 2 is 0 (value of val is even), or returns false is val % 2 is 1 (value of val is odd)
Just for information: Modulo operator returns the remainder(a number) when val is divided by any number

Javascript chained inequality gives bizarre results [duplicate]

This question already has answers here:
Can I use chained comparison operator syntax? [duplicate]
(6 answers)
Closed 8 years ago.
(0 <= 0 <= 0) === false
(-1 < 0 <= 0 <= 0) === true
What's going on here? Does Javascript actually have inequality chaining that's just wrong in some cases?
Typed up the question and then was struck by the answer. Javascript does not have inequality chaining. Rather, 0 <= 0 <= 0 becomes true <= 0, which is evaluated as 1 <= 0. Indeed, 0 < 0 <= 0 evaluates to true.
There is no chaining of operator but precedence. Here all the operators have the same priority so the operations are done from left to right.
When your comparison involves a boolean, the MDN explains how the comparison works :
If one of the operands is Boolean, the Boolean operand is converted to
1 if it is true and +0 if it is false.
This means the first operation is decomposed according to priorities as
((0 <= 0) <= 0)
which is
true <= false
which is
false
And the second one is
(true <= 0) <= 0
which is
false <= 0
which is true.

Understanding this Javascript code using % modulus

Im currently in process of learning Javascript. And I have seen the following code, which confuses me.
Description of code:
Starting on line 1, the function isOdd takes a number n and returns a boolean (true or false) stating whether the number is odd or not.
Code
var isOdd = function (n) {
if (n % 2 === 0) {
return false;
} else {
return true;
}
};
var isEven = function(n) {
if(n % 2 === 0) {
return true;
} else {
return false;
}
};
Where I am confused.
The code:
n % 2 === 0
I have always taken the following to be the description for %:
% Is the modulus operator. It returns the remainder of dividing number1 by number2.
Which would mean that the if statement in the function isOdd returns false is the difference between n and 2 is 0. But its meant to mean if n is divisible by 2 (even) return false.
I just dont see how its doing that.
In my mind, if we take the even number 30. Apply it to n % 2. We get 15, which is remainder of dividing 30 by 2. 15 does not equal 0, but 30 is an even number, and with this code it would be seen as odd.
Can someone explain this?
The line in question:
if (n % 2 === 0) {
return false;
}
Means "if when you divide n by 2 the remainder is zero, then return false (i.e. n is not odd)".
The "remainder" is whatever is left over when you subtract the nearest multiple, so for example "64 % 10" is 4, since the nearest multiple of 10 is 60, leaving 4.
Taking your example and putting it another way, 30/2 is 15, 30%2 is zero (i.e. whatever is left over after 30/2). Here's more info on the remainder after division.
You're confusing Quotient and Remainder.
When you divide 30 by 2, integer quotient is 15, and remainder is 0. You can also calculate remainder by multiplying integer quotient by divisor and subtracting it from dividend. So for this division remainder is 30 (dividend) - 15 (quotient) * 2 (divisor) = 0.
If n can be divided by 2 it means it's even ->
which means it's not odd ->
isOdd is false

shortest expression to return false for negative number and the number itself for positive number (or zero)

What is the shortest expression I can use to return false for all numbers < 0 and the number itself for all numbers >= 0?
Left is what I have, right is want I want to be returned.
-3: false
-1: false
0: 0
1: 1
23: 23
Something really short like:
(!!number) <-- (doenst work)
If you want something shorter, you could do:
return number >= 0 && number;
If number >= 0 is false, then && will evaluate to the left operand (i.e. false). Otheriwse, it evaluates to the right operand (i.e. the number).
without any checking whether number is actually a number:
return number < 0 ? false : number;
return number < 0 ? false : number;
A very short one:
0>number?!1:number
Minified: 0>n?!1:n
Hint: !1 === false
Demo:
var numbers = [
-5, // > false
0, // > 0
5 // > 5
];
numbers.forEach(function(n) {
console.log(
0>n?!1:n
);
});

Categories

Resources