how to convert -1 to 1 with javascript? - javascript

how to convert -1 to 1 with javascript ?
var count = -1; //or any other number -2 -3 -4 -5 ...
or
var count = 1; //or any other number 2 3 4 5 ...
result should be
var count = 1; //or any other number 2 3 4 5 ...

count = Math.abs(count)
// will give you the positive value of any negative number

The abs function turns all numbers positive: i.e Math.abs( -1 ) = 1

Alternative approach (might be faster then Math.abs, untested):
count = -5;
alert((count ^ (count >> 31)) - (count >> 31));
Note that bitwise operations in javascript are always in 32-bit.

If the number of interest is input... In addition to Math.abs(input)....
var count = (input < 0 ? -input : input);
jsFiddle example
(edit: as Some pointed out -input is faster than -1 * input)
The above makes use of the Javascript conditional operator. This is the only ternary (taking three operands) Javascript operator.
The syntax is:
condition ? expr1 : expr2
If the condition is true, expr1 is evaluated, if it's fales expr2 is evaluated.

Related

Function explanation using the ?: ( conditional operator in javascript )

I'm trying to understand this function that returns the ordinal numbers when we give it a number.
Unfortunately I couldn't figure out how this is working with the conditional operator, could someone explain it to me?
function getOrdinalNum(n) {
return n + (n > 0 ? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10] : '');
}
The best way to explain this sort of thing is to break it down into a function with if statements. Take a look at the newFunction it does the same thing that the function getOrdinalNum does:
function getOrdinalNum(n) {
return n + (n > 0 ? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10] : '');
}
function newFunction(n) {
if (n > 0) {
if ((n > 3 && n < 21) || n % 10 > 3) {
return n + 'th'; // essentially returning ['th', 'st', 'nd', 'rd'][0];
} else {
return n + ['th', 'st', 'nd', 'rd'][n % 10];
}
}
}
for(let i = 1; i < 9; i++) {
console.log(getOrdinalNum(i));
console.log(newFunction(i));
}
Break it down like this:
n +
(
n > 0
? ['th', 'st', 'nd', 'rd']
[
(n > 3 && n < 21) || n % 10 > 3
? 0
: n % 10
]
: ''
);
Here:
JS checks if n > 0. If yes then:
An array is created ['th', 'st', 'nd', 'rd']
The next [] tells us a property accessor will follow
Which property is determined by the ternary operation. Either 0 (which will mean (th) or the result of n & 10
And the result of accessing that property is added whatever n was.
If n is smaller or equal with 0 then whatever n was, an empty string is added to it.
It helps to know the operator precedence in JS. Give it a goooood read and practice some.
Operators (unary, binary, ternary)
The ternary conditional operator is different than most other operators in that it takes 3 operands instead of one or two.
You are used to unary operators like the negative symbol in -5 which takes one operand and makes it a negative value.
There is also the binary concatenation operator + used like 'hello ' + 'world'. Here there are two operands which produce the value 'hello world'.
The ternary conditional operator has the form
/* conditional expression */ ? /* expression if truthy */ : /* expression if not truthy*/
Where the comments are the operands for you to fill in with the more complex code from your example. // if n > 0 then the complex expression, otherwise the empty string
Simple example.
Try to run the following statements in your browser.
console.log(true ? 'true value' : 'false value');
var x = 3 > 1 ? 'true value' : 'false value';
console.log(x);
prompt('try entering a blank space, or characters') ? 'a' : 'b';
The code flows much the same as the other answers describe. The first expression is emitted if the condition is truthy otherwise the second expression is emitted.
Here are some docs on what I mean by truthy

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

Detect if number change from negative to positive or positive to negative

How to detect if positive or nagative changes ?
Example :
1 change to 2 = false
0 change to 1 = false
Because both are positive numbers
1 change to -1 = true
0 change to -1 = true
Because positive change to negative
-1 change to 0 = true
-1 change to 1 = true
Because negative change to positive
I do like..
var a_test,b_test;
if(a<0) {
a_test = 'negative';
} else {
a_test = 'positive';
}
if(b<0) {
b_test = 'negative';
} else {
b_test = 'positive';
}
if(a_test!==b_test) {
alert('Yeah!');
}
For test : http://jsfiddle.net/e9QPP/
Any better coding for do something like this ?
Wiki : A negative number is a real number that is less than zero
According to the Zen of Python,
Readability counts.
So, I present more readable and code-review passing version
if (a < 0 && b >= 0 || a >= 0 && b < 0) {
alert("Yeah");
}
You seem to want
if (a*b<0) alert('Yeah!');
If you want to consider 0 as a positive number, you may use
if (a*b<0 || (!(a*b) && a+b<0)) alert('Yeah!');
Taking a suitable sign function:
function sign(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
}
Then your problem can be expressed in clear and (hopefully) simple terms:
if (sign(a) !== sign(b)) {
// Your code here
}
Based on your criteria, it seems you simply want to compare the signs of the two numbers. The sign is stored in the highest bit of the number, therefore, to compare the signs, we can simply shift all the other bits off the number, and compare the signs.
Numbers in JavaScript are 64 bit (double), so we need to shift off the 63 bits preceding the sign:
if (a >>> 63 !== b >>> 63) alert('Yeah!');
Here is a jsFiddle demo
Here is a jsPerf comparison based on the 4 methods offered here.
Please note that this assumes that the numbers are 64 bit. I don't know if the spec restricts it to 64-bit, but it's plausible that there are browsers out there (or will be one day) where numbers are represented by perhaps a 128-bit number or greater.
Maybe a bit late, but I had the same problem.
Assuming you now that a and b are numbers why not:
if(a < 0 ? b >=0 : b < 0){
// your code here
}

What does % do in JavaScript?

What does the % do in JavaScript?
A definition of what it is and what it does would be much appreciated.
It's a modulo operator. See this documentation or the specification for more information on JavaScript arithmetic operators.
% (Modulus)
The modulus operator is used as follows:
var1 % var2
The modulus operator returns the first operand modulo the second
operand, that is, var1 modulo var2, in the preceding statement, where
var1 and var2 are variables. The modulo function is the integer
remainder of dividing var1 by var2. For example, 12 % 5 returns 2. The
result will have the same sign as var1; that is, −1 % 2 returns −1.
ES6 Update:
As explained in other answers, it returns the remainder after dividing the dividend by divisor, however this is no longer modulo operator, this is remainder operator. the difference being that the modulo operator result would take the sign of the divisor, not the dividend.Quoted from MDN
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of ECMAScript, the difference being that the modulo operator result would take the sign of the divisor, not the dividend.
Example:
-10 % 3 // -1
10 % -3 // 1
It returns the remainder of a division operation. 5%2 returns 1
It is a modulo operator.
It calculates the remainder.
If we do 23 % 10,
first, we divide 23 by 10 which equals 2.3
then take .3 * (the divisor) 10
= 3
That would be the modulo operator.
It returns the remainder of a division operation:
var remainder = 3 % 2; // equals 1
In JavaScript, % is a remainder operator (Not a modulo operator).
remainder operator % (uses Math.truc()):
remainder = -5 % 3 = -2
How is it calculated ?
quotient = Math.trunc(dividend / divisor) = Math.trunc(-5 / 3) = -1;
remainder = dividend - divisor * quotient = -5 - (3 * -1) = -2
modulo function (uses Math.floor()):
modulo(-5,3) = 1
How is it calculated ?
quotient = Math.floor(dividend / divisor) = Math.floor(-5 / 3) = -2;
remainder = dividend - divisor * quotient = -5 - (3 * -2) = 1
For positive numbers, both remainder operator and modulo gives the same result.
5 % 3 = 2
modulo(5,3) = 2
In JavaScript, there is no build-in function for doing modulo operation, so you need to write on your own by using Math.floor() as above. Alternatively even you could easily write using the remainder operator as shown below.
function modulo(n, m) {
return ((n % m) + m) % m;
}
Just in case, if someone is looking for a real modulo function (which would always get the sign of the divisor), you can use this:
function Modulo(num, denom)
{
if (num%denom >= 0)
{
return Math.abs(num%denom);
}
else
{
return num%denom + denom;
}
}
The Math.abs is to prevent the case -12%12 → -0, which is considered equal to 0 but displayed as -0.
Modulus (%) operator returns the remainder.
If either value is a string, an attempt is made to convert the string to a number.
alert(5%3) will alert 2
% performs as the modulo operator, return division reminder. Example:
<script>
var x = 5;
var y = 2;
var z = x % y;
alert(z);
</script>
This will alert 1.
This is what I would do to getModulus, given k > 0. I find it more intuitive as Math.floor(num / k ) in js is exactly num // k in python.
function getModulus(num, k) {
return num - Math.floor(num / k ) * k
}

Categories

Resources