Sum of Digits / Digital Root codewars kata [duplicate] - javascript

This question already has answers here:
Recursive function returns undefined
(3 answers)
Closed 1 year ago.
Please, help me. I don't understand. Why second solution returns undefined?
function digital_root(n) {
return n < 10 ? n : digital_root(n.toString().split('').map(Number).reduce((a, b) => a + b));
}
console.log(digital_root(12345678));
// expected output: 9
function digital_root(n) {
if (n < 10) {
return n;
} else {
digital_root(n.toString().split('').map(Number).reduce((a, b) => a + b));
}
}
console.log(digital_root(12345678));
// output: undefined

This happens because your second code ignores the value you get returned from the recursive call. You should do something with it... return it.
function digital_root(n) {
if (n < 10) {
return n;
} else {
return digital_root(n.toString().split('').map(Number).reduce((a, b) => a + b));
}
}
console.log(digital_root(12345678));
Unrelated, but you can combine split and map by doing Array.from. Also the first version joins the two return statements with the conditional operator into a return of one expression:
const digital_root = n => n < 10 ? n
: digital_root(Array.from(n.toString(), Number).reduce((a, b) => a + b));
console.log(digital_root(12345678));

Related

(JavaScript) Why my if/else code didn't work? [duplicate]

This question already has answers here:
How do you use the ? : (conditional) operator in JavaScript?
(20 answers)
Closed 1 year ago.
I need to make a fibonacci sequence and I found this code below here. When I try to understand all code I saw "(i <= 1) ? i : arr[i-2] + arr[i-1]", I thought that was an simple if else shortcut condition, and I try to replace by the extended way just to be sure (see the last code). But now the code didn't work...
Stackoverflow code:
function fib(n) {
return new Array(n).fill(1).reduce((arr, _, i) => {
arr.push((i <= 1) ? i : arr[i - 2] + arr[i - 1])
return arr
}, []);
}
console.log(fib(10))
My code with (extended if else):
function fib(n) {
return new Array(n).fill(1).reduce((arr, _, i) => {
arr.push(
if (i <= 1) {
i
} else {
arr[i - 2] + arr[i - 1]
})
return arr
}, []);
}
console.log(fib(10))
Why my code is not equivalent to the code above?
Basically what #esqew said.
“I thought that was an simple if else shortcut condition” While this
is kind of close to true, any old if/else is not a drop-in
replacement for something that was originally written using the
ternary operator ?
Replacing a Conditional Operator with an if statement directly will throw an error.
If you want to use if/else syntax inside a function parameter you could write the code as a function in the form of an IIFE.
(() => {
if (i <= 1) {
return i;
} else {
return arr[i - 2] + arr[i - 1];
}
})();
Demo:
function fib(n) {
return new Array(n).fill(1).reduce((arr, _, i) => {
arr.push(
(() => {
if (i <= 1) {
return i;
} else {
return arr[i - 2] + arr[i - 1];
}
})()
);
return arr;
}, []);
}
console.log(fib(10));

In JavaScript, how can I create one function that takes two numbers and a mathematical operator + - / * perform a calculation with the given numbers [duplicate]

This question already has answers here:
Javascript function - converting string argument to operator
(2 answers)
Closed 1 year ago.
Just starting learn js, how can I get results like what shows in the examples.
So the require is like this:
Create a function that takes two numbers and a mathematical operator + - / * and will perform a calculation with the given numbers.
Examples
calculator(2, "+", 2) ➞ 4
calculator(2, "*", 2) ➞ 4
calculator(4, "/", 2) ➞ 2
Notes
If the input tries to divide by 0, return: "Can't divide by 0!"
function calculator (a, b) {
let output = 0;
output = a+b;
return output;
}
console.log(calculator(2,2));
Here is what I wrote, only for performing "+".
I thought maybe I should try to add another parameter to repersent "+*/", but I can't get it right.
Anyone can help with it?
Thanks
This should work
function calculator (a, b, c) {
let output = 0;
try {
switch(c) {
case '+':
output = a + b
break;
case '*':
output = a * b
break;
case '-':
output = a - b
break;
case '/':
if (b === 0) {
throw "Can't divide by 0!"
} else {
output = a / b
}
break;
}
}
catch(e) {
console.log("There's an error: ", e)
}
return output;
}
console.log(calculator(2,2,'*'));
Here is the function:
const calculator = (a, b, operation) => {
if (operation === '+') return a + b;
if (operation === '-') return a - b;
if (operation === '*') return a * b;
if (operation === '/') return b === 0 ? "Can't divide by 0!" : a / b;
}
console.log(calculator(10, 10, "*"));

How do two ternary operators work together in JS?

So I was doing a code problem online and one of the solutions showed the following
function electionsWinners(votes, k) {
var max=Math.max(...votes)
var r=votes.filter(x=>x+k>max||x===max).length
return k?r:r==1?1:0
}
I don't think the specifics of the problem are relevant, I'm more interested in how the return statement works. I don't understand at all what gets returned, it seems that 2 ternary operators are being used but I'm not sure, can anyone help me understand how exactly this return statement functions?
Yes 2 ternary operators
return k?r:r==1?1:0
i will put the code with complete IF
if(k) //not is null
return r;
else
{
if(r==1)
return 1;
else
return 0;
}
If you convert it to if else statement then you'll better understand what's going on:
if (k) {
return r;
} else if (r === 1) {
return 1;
} else {
return 0;
}
Or
if (k) {
return r;
}
if (r === 1) {
return 1;
}
return 0;
You can look at
k?r:r==1?1:0
as a single expression. Each ? is connected to its immediately following :, so it's equivalent to:
k ? r : (r==1 ? 1 : 0)
where the second conditional operator takes effect only if the k is falsey. In that second conditional, if r is 1, 1 is returned, else 0 is returned.
Might be clearer with indentation:
return (k
? r
: (r == 1
? 1
: 0
)
);
The first test is k ? is k not 0/undefined/null? If so, return r (r) else : if r is 1 (r==1 ?) return 1 (1) otherwise return 0 (0))

How to implement Fibonacci number using recursion in JavaScript [duplicate]

This question already has answers here:
JavaScript Fibonacci breakdown
(3 answers)
Closed 3 years ago.
I tried playing around with recursion in javascript. I wrote a function for the Fibonacci sequence. However, if only works if the argument is 0
fib = (x)=>{
if (x == 0 || x ==1) {
return 1
} else {
return fib(x-1) + fib(x+1)
}
}
It returns 1 for 1, but a number above 0 I get the error maximum call stack size exceeded
This is not the Fibonacci sequence. This is the Fibonacci sequence:
fib = (x) => {
if (x == 0 || x == 1) {
return 1;
} else {
return fib(x - 1) + fib(x - 2);
}
}
for (let i = 0; i < 10; i++) {
console.log(fib(i));
}
In its simplest form, of course. If you go too far beyond 10, you'll experience what an exponential cost of computation can do to a computer.
You need the value of the second last iteration, no an iteration ahead.
Please have a look here, too: Fibonacci number.
const fib = x => {
if (x === 0 || x === 1) {
return 1;
}
return fib(x - 2) + fib(x - 1);
};
console.log(fib(7));

VAL() function in JavaScript

In continuing my question from yesterday, I have the following code:
function VAL(str) {
// IF LEFT(str,1) IN('0,1,2,3,4,5,6,7,8,9,.) THEN
return parseFloat(str);
return 0;
}
function LEFT(str,n) {
if (n <= 0) return "";
if (n >= str.length) return str;
return str.substring(0,n);
}
Q: How do I write the commented line above such that it says "IF the first character is 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or period, then return parseFloat(str)"?
You don't need that check. If the first character is not a digit, then parseFloat returns NaN.
function VAL(str) {
var f = parseFloat(str);
return isNaN(f) ? 0 : f;
}
I would use Regex
if (str.match(/([0-9]|\./)) return parseFloat(str);
set = "0123456789";
if (set.indexOf(LEFT(str, 1)) > -1 return parseFloat(str);

Categories