Understanding custom abs function in JavaScript - javascript

I hope my logic isn't flawed but I'm reading the Definitive Guide to JavaScript and I don't understand how this custom abs function works...
function abs(x) {
if (x >= 0) {
return x;
} else {
return -x;
}
}
I recrafted it using a ternary operator in an attempt to understand it...
var res = (x >= 0) ? x : -x;
return res;
... but I still don't get how it works.
Say I use -10 as x, how does it return +10? How does the sign reverse?

function abs(x) {
if (x >= 0) {
//If the number passed is greater than or equal to zero (positive)
//return it back as is
return x;
} else {
//If less than zero (negative)
//return the negative of it (which makes it positive)
// -(-10) === 10
return -x;
}
}

Negative 10 is not greater than or equal to 0, so its opposite is returned.
Placing a negative sign in front of a variable is the same thing as multiplying it by negative 1.

it look as
var res = (x >= 0) ? 1 * x : -1 * x;

Say I use -10 as x, how does it return +10? How does the sign reverse?
That's because of this check:
x >= 0
If number is 0 or greater it returns it else returns negative version which becomes positive because of - sign before it.

Related

Is finding the factorial of 5000 possible in javascript

I want to find the factorial of 5000 but once I try to pass 100 it'll return infinity. Is there are way to bypass this and get the result? I am trying to get the time it takes to solve this.
function testSpeed(n) {
if (n > 0 && n <= 1) {
return 1;
} else {
return n * testSpeed(n-1);
}
}
console.log(testSpeed(5000));
As you've noticed, Javascript numbers can only get so big before they just become "Infinity". If you want to support bigger numbers, you'll have to use BigInt.
Examples:
// Without BigInt
console.log(100 ** 1000) // Infinity
// With BigInt
// (stackOverflow doesn't seem to print the result,
// unless I turn it into a string first)
console.log(String(100n ** 1000n)) // A really big number
So, for your specific bit of code, all you need to do is turn your numeric literals into BigInt literals, like this:
function testSpeed(n) {
if (n > 0n && n <= 1n) {
return 1n;
} else {
return n * testSpeed(n-1n);
}
}
console.log(String(testSpeed(5000n)));
You'll find that youe computer can run that piece of code in a snap.
This seems to give the correct result (according to https://coolconversion.com/math/factorial/What-is-the-factorial-of_5000_%3F)
const longFactorial = (num) => {
let result = num;
for (let i = 1n; i < num; i++) {
result = result * (num - i)
}
return String(result);
}
console.log(longFactorial(5000n));
I can receive for 170! maximum:
function factorial (y){
if (y ==0 || y ==1){
return 1;
}
else {
f = y - 1;
while (f >= 1) {
y = y * f;
f--;
}
return y;
}
}
console.log(factorial(170));

Do you know of a computer algorithm to solve the ability to divide without division operators?

Through applying a computer science algorithm in JavaScript, could you solve the following question?
The function accepts a numerator and denominator in the form of a positive or negative integer value.
You can not use '*', '/' or '%'.
function divide(num, denom) {
// ...
}
divide(6, 2)
divide(-10, 5)
divide(7, 2)
divide(-5, 10)
I am curious to know if there is a known computer science algorithm out there that can solve this.
I saw this question and had to take a crack at it, I've implemented a solution that can get decimal places up to a specified precision as well as handle negatives, it uses a recursive approach and some string manipulation.
// Calculate up to decimal point
const MAX_PRECISION = 6;
function divide(numerator, denominator, answer=0, decimals=MAX_PRECISION)
{
// Account for negative numbers
if ((numerator < 0 || denominator < 0))
{
// If both are negative, then we return a positive, otherwise return a negative
if (numerator < 0 && denominator < 0)
return divide(Math.abs(numerator), Math.abs(denominator))
else return -divide(Math.abs(numerator), Math.abs(denominator));
}
// Base case return if evenly divisble or we've reached the specificed percision
if (numerator == 0 || decimals == 0) return answer;
// Calculate the decimal places
if (numerator < denominator)
{
// Move the decinal place to the right
const timesTen = parseInt(numerator + "0");
// Calcualte decimal places up to the certain percision
if (decimals == MAX_PRECISION)
return parseFloat(answer + "." + divide(timesTen, denominator, 0, decimals-1));
else return answer + "" + divide(timesTen, denominator, 0, decimals-1);
}
// Perform the calculations in a tail-recursive manor
return divide(numerator-denominator, denominator, answer+1, decimals);
}
// Test Cases
console.log(divide(10, 2));
console.log(divide(10, -2));
console.log(divide(-7, -4));
console.log(divide( 1, -2));
console.log(divide(11, 3));
console.log(divide(22, 7));
You can try Something like:
function divide(num, denom) {
var count = 0;
while (num > 0) {
num = num - denom
if (num >= 0) {
count ++;
}
}
return count;
}

Javascript check if a decimal is negative

How would i check if a decimal is negative? Because the if statement automatically turns it into a number...
Example:
var x = -0.24324;
how would i parse it so it tells me x is negative/positive?
Thanks
Edit: Maybe i phrased it badly, the variable changes so something it will be positive like 0.00000001, sometimes -0.0003423423, sometimes 0.0000000234
If i put it in a if statement everything is automatically turned into 0 right? And i can't use a parseFloat in the if statement?
Just check if x less than zero since it's a number:
if (x < 0) {
// it's negative
}
You can use isNaN() function to check whether it is valid number or not.
If it is, then you can check for positive or negative value.
Something like this:
var x = "-123"
var y = -456;
var z = '-123a';
if(!isNaN(x) && x < 0) {
console.log(x + ' is negative');
}
if(!isNaN(y) && y < 0) {
console.log(y + ' is negative');
}
if(!isNaN(z) && z < 0) {
console.log(z + ' is negative');
}
const num = -8;
// Old Way
num === 0 ? num : (num > 0 ? 1 : -1); // -1
// ✅ ES6 Way
Math.sign(num); // -1

Recursively find the sum of a number's digits w/ RegEx and w/o Eval()

Can anyone suggest an implementation that avoids eval, hopefully uses regex, and executes in 6 lines or less? Its a fun problem.
Input: 12 => 3
Input: 235 => 10 => 1
function baseNumber(n){
var x = eval(n.toString().replace(/(\d)(?=\d)/g, '$1+'))
if(x>9){
return baseNumber(x)
} else {
return x
}
}
If you need to use regex (you could also do the same thing without regex and using split)
function baseNumber(n){
if (n > 9)
return baseNumber(n.toString().match(/(\d)/g).reduce(function(a, b) { return a + Number(b) }, 0))
else
return n;
}
The reduce does the summing up. The match returns the array of matches (i.e. digits)
If you want to handle decimals and negative numbers change the if (n > 9) check to if (n.toString().length > 1)
What about this one:
var input = 235;
while(input > 9) input = String(input).match(/[\d]/g).reduce(function(sum, currentValue) {
return sum + parseInt(currentValue);
}, 0);
console.log(input);
Try casting n to String , utilizing String.prototype.split() , String.prototype.replace() , Array.prototype.splice() , Number() , do.. while loop
function baseNumber(n) {
var x = String(n).replace(/[^\d]/g, "").split(""), y = 0;
do { y += Number(x.splice(0, 1)) } while (!!x.length);
return y > 9 ? baseNumber(y) : y
}
console.log(baseNumber("abc12"), baseNumber("def235"))

Testing whether a value is odd or even

I decided to create simple isEven and isOdd function with a very simple algorithm:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.
Use modulus:
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
You can check that any value in Javascript can be coerced to a number with:
Number.isFinite(parseFloat(n))
This check should preferably be done outside the isEven and isOdd functions, so you don't have to duplicate error handling in both functions.
I prefer using a bit test:
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
This tests whether the first bit is on which signifies an odd number.
How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)
function isEven(n) {
return /^-?\d*[02468]$/.test(n);
}
function isOdd(n) {
return /^-?\d*[13579]$/.test(n);
}
Note: there are also negative numbers.
function isOddInteger(n)
{
return isInteger(n) && (n % 2 !== 0);
}
where
function isInteger(n)
{
return n === parseInt(n, 10);
}
Why not just do this:
function oddOrEven(num){
if(num % 2 == 0)
return "even";
return "odd";
}
oddOrEven(num);
To complete Robert Brisita's bit test .
if ( ~i & 1 ) {
// Even
}
var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);
var isEven = function(number) {
// Your code goes here!
if (number % 2 == 0){
return(true);
}
else{
return(false);
}
};
A few
x % 2 == 0; // Check if even
!(x & 1); // bitmask the value with 1 then invert.
((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value
~x&1; // flip the bits and bitmask
We just need one line of code for this!
Here a newer and alternative way to do this, using the new ES6 syntax for JS functions, and the one-line syntax for the if-else statement call:
const isEven = num => ((num % 2) == 0);
alert(isEven(8)); //true
alert(isEven(9)); //false
alert(isEven(-8)); //true
A simple modification/improvement of Steve Mayne answer!
function isEvenOrOdd(n){
if(n === parseFloat(n)){
return isNumber(n) && (n % 2 == 0);
}
return false;
}
Note: Returns false if invalid!
Different way:
var isEven = function(number) {
// Your code goes here!
if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};
isEven(69)
Otherway using strings because why not
function isEven(__num){
return String(__num/2).indexOf('.') === -1;
}
if (testNum == 0);
else if (testNum % 2 == 0);
else if ((testNum % 2) != 0 );
Maybe this?
if(ourNumber % 2 !== 0)
var num = someNumber
isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;
for(var a=0; a<=20;a++){
if(a%2!==0){
console.log("Odd number "+a);
}
}
for(var b=0; b<=20;a++){
if(b%2===0){
console.log("Even number "+b);
}
}
Check if number is even in a line of code:
var iseven=(_)=>_%2==0
This one is more simple!
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);
To test whether or not you have a odd or even number, this also works.
const comapare = x => integer(checkNumber(x));
function checkNumber (x) {
if (x % 2 == 0) {
return true;
}
else if (x % 2 != 0) {
return false;
}
}
function integer (x) {
if (x) {
console.log('even');
}
else {
console.log('odd');
}
}
Using modern javascript style:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = n=> isOdd(+n+1)
function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}
when 0/even wanted but
isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false
​
if (i % 2) {
return odd numbers
}
if (i % 2 - 1) {
return even numbers
}

Categories

Resources