Calling a value of a ternary operator in 1 line - javascript

I have this ternary operator
function digPow(n, p){
return Number.isInteger((""+n).split("").map((num,index) => Math.pow(parseInt(num),(p+index))).reduce((a, b) => a + b, 0)/n) ? (""+n).split("").map((num,index) => Math.pow(parseInt(num),(p+index))).reduce((a, b) => a + b, 0)/n : -1;
}
As you can see this is a very long 1 liner. My question is, how do I recall the value inside the Number.isInteger() so that I don't have to repeat it again for the ternary operator in only 1 line.
This is the code I need a value from:-
(""+n).split("").map((num,index) => Math.pow(parseInt(num),(p+index)))
.reduce((a, b) => a + b, 0)/n
Is there any syntax for this? I am relatively new to JS
EDIT: The main question is actually: "Is it possible to call the value from inside a ternary operator without using a variable"
EDIT-2: Sorry for my bad coding. Here is a simpler way to ask my question
const x = 6
const y = 3
console.log(Number.isInteger(x+y/3) ? x+y/3 : -1)
Is it possible to recall the x+y/3 value without repeating it or making a new variable?

Not exactly sure, what your function is doing or what arguments it's supposed to take, but you could use a Self-Executing Anonymous Function
aka IIFE (Immediately Invoked Function Expression).
Let's start by formatting what you currently have:
const digPow = (n, p) => Number.isInteger(
("" + n)
.split("")
.map((num, index) => Math.pow(parseInt(num), (p + index)))
.reduce((a, b) => a + b, 0) / n
)
? ("" + n)
.split("")
.map((num, index) => Math.pow(parseInt(num), (p + index)))
.reduce((a, b) => a + b, 0) / n
: -1;
console.log(digPow(6, 3)); // 36
It looks like this part is inside the condition and also a return if the result is an integer:
("" + n)
.split("")
.map((num, index) => Math.pow(parseInt(num), (p + index)))
.reduce((a, b) => a + b, 0) / n
You can reduce your logic to the following (pseudo-code):
const digPow = (x => Number.isInteger(x) ? x : -1)(split/map/reduce/divide);
Let's pass that into an IIFE:
const digPow = (n, p) => (
(value) => Number.isInteger(value) ? value : -1)
(("" + n)
.split("")
.map((num, index) => Math.pow(parseInt(num), (p + index)))
.reduce((a, b) => a + b, 0) / n);
console.log(digPow(6, 3)); // 36

Related

Not able to solve the power sum for all cases using recursion

I have written the code of this problem but it works for only 70% of the test cases. I can't figure out what is wrong with it. Please help.
Problem:-
Find the number of ways that a given integer, X, can be expressed as the sum of the Nth powers of unique, natural numbers in the range of [1,25] both inclusive.
Hint:-
The answer will be (1^2 + 3^2).
My code is not working for x = 100 and n = 2. The output should be 3 but it returns 33.
let x = 100;
let n = 2;
let num = 0;
let index = 1;
function power(x, n, num, index, ways = 0) {
if (x === num) {
return 1;
}
if (x < num) {
return 0;
}
for (let i = index; i <= 25; i++) {
ways += power(x, n, (num + ((i) ** n)), index + 1);
}
return ways;
}
console.log(power(x, n, num, index));
Your logic is almost right. But you're not properly removing duplicate values and ending up including things like 9^2 + 3^2 + 3^2 + 1^2 or 5^2 + 5^2 + 5^2 + 4^2 + 3^2.
You need to change the recursive index you pass. You shouldn't use your index parameter but your loop iterator, i:
let x = 100;
let n = 2;
let num = 0;
let index = 1;
function power(x, n, num, index, ways = 0) {
if (x === num) {
return 1;
}
if (x < num) {
return 0;
}
for (let i = index; i <= 25; i++) {
// ways += power(x, n, (num + ((i) ** n)), index + 1);
// v-^
ways += power(x, n, (num + ((i) ** n)), i + 1);
}
return ways;
}
console.log(power(x, n, num, index));
I figured this out fairly quickly by writing my own version of the function from scratch, and getting the exact same wrong result. I added some logging and realized the problem and was able to spot it quickly. This translated easily to your code.
But I think my function is cleaner, so I'm including it here. It does much the same logic, but in a cleaner functional manner:
const range = (lo, hi) =>
Array .from ({length: hi - lo + 1}, (_, i) => i + lo)
const sum = (ns) =>
ns .reduce ((a, b) => a + b, 0)
const countPowerSums = (n, p, i = 1) =>
n < 0
? 0
: n == 0
? 1
: sum (range (i, 25) .map (b => countPowerSums (n - b ** p, p, b + 1)))
console .log (countPowerSums (100, 2))

Recursive call to a monotonic function with an IIFE stop or creating add function that returns unknown num of functions for adding the next number [duplicate]

I need a js sum function to work like this:
sum(1)(2) = 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10
etc.
I heard it can't be done. But heard that if adding + in front of sum can be done.
Like +sum(1)(2)(3)(4). Any ideas of how to do this?
Not sure if I understood what you want, but
function sum(n) {
var v = function(x) {
return sum(n + x);
};
v.valueOf = v.toString = function() {
return n;
};
return v;
}
console.log(+sum(1)(2)(3)(4));
JsFiddle
This is an example of using empty brackets in the last call as a close key (from my last interview):
sum(1)(4)(66)(35)(0)()
function sum(firstNumber) {
let accumulator = firstNumber;
return function adder(nextNumber) {
if (nextNumber === undefined) {
return accumulator;
}
accumulator += nextNumber;
return adder;
}
}
console.log(sum(1)(4)(66)(35)(0)());
I'm posting this revision as its own post since I apparently don't have enough reputation yet to just leave it as a comment. This is a revision of #Rafael 's excellent solution.
function sum (n) {
var v = x => sum (n + x);
v.valueOf = () => n;
return v;
}
console.log( +sum(1)(2)(3)(4) ); //10
I didn't see a reason to keep the v.toString bit, as it didn't seem necessary. If I erred in doing so, please let me know in the comments why v.toString is required (it passed my tests fine without it). Converted the rest of the anonymous functions to arrow functions for ease of reading.
New ES6 way and is concise.
You have to pass empty () at the end when you want to terminate the call and get the final value.
const sum= x => y => (y !== undefined) ? sum(x + y) : x;
call it like this -
sum(10)(30)(45)();
Here is a solution that uses ES6 and toString, similar to #Vemba
function add(a) {
let curry = (b) => {
a += b
return curry
}
curry.toString = () => a
return curry
}
console.log(add(1))
console.log(add(1)(2))
console.log(add(1)(2)(3))
console.log(add(1)(2)(3)(4))
Another slightly shorter approach:
const sum = a => b => b? sum(a + b) : a;
console.log(
sum(1)(2)(),
sum(3)(4)(5)()
);
Here's a solution with a generic variadic curry function in ES6 Javascript, with the caveat that a final () is needed to invoke the arguments:
const curry = (f) =>
(...args) => args.length? curry(f.bind(0, ...args)): f();
const sum = (...values) => values.reduce((total, current) => total + current, 0)
curry(sum)(2)(2)(1)() == 5 // true
Here's another one that doesn't need (), using valueOf as in #rafael's answer. I feel like using valueOf in this way (or perhaps at all) is very confusing to people reading your code, but each to their own.
The toString in that answer is unnecessary. Internally, when javascript performs a type coersion it always calls valueOf() before calling toString().
// invokes a function if it is used as a value
const autoInvoke = (f) => Object.assign(f, { valueOf: f } );
const curry = autoInvoke((f) =>
(...args) => args.length? autoInvoke(curry(f.bind(0, ...args))): f());
const sum = (...values) => values.reduce((total, current) => total + current, 0)
curry(sum)(2)(2)(1) + 0 == 5 // true
Try this
function sum (...args) {
return Object.assign(
sum.bind(null, ...args),
{ valueOf: () => args.reduce((a, c) => a + c, 0) }
)
}
console.log(+sum(1)(2)(3,2,1)(16))
Here you can see a medium post about carried functions with unlimited arguments
https://medium.com/#seenarowhani95/infinite-currying-in-javascript-38400827e581
Try this, this is more flexible to handle any type of input. You can pass any number of params and any number of paranthesis.
function add(...args) {
function b(...arg) {
if (arg.length > 0) {
return add(...[...arg, ...args]);
}
return [...args, ...arg].reduce((prev,next)=>prev + next);
}
b.toString = function() {
return [...args].reduce((prev,next)=>prev + next);
}
return b;
}
// Examples
console.log(add(1)(2)(3, 3)());
console.log(+add(1)(2)(3)); // 6
console.log(+add(1)(2, 3)(4)(5, 6, 7)); // 28
console.log(+add(2, 3, 4, 5)(1)()); // 15
Here's a more generic solution that would work for non-unary params as well:
const sum = function (...args) {
let total = args.reduce((acc, arg) => acc+arg, 0)
function add (...args2) {
if (args2.length) {
total = args2.reduce((acc, arg) => acc+arg, total)
return add
}
return total
}
return add
}
document.write( sum(1)(2)() , '<br/>') // with unary params
document.write( sum(1,2)() , '<br/>') // with binary params
document.write( sum(1)(2)(3)() , '<br/>') // with unary params
document.write( sum(1)(2,3)() , '<br/>') // with binary params
document.write( sum(1)(2)(3)(4)() , '<br/>') // with unary params
document.write( sum(1)(2,3,4)() , '<br/>') // with ternary params
ES6 way to solve the infinite currying. Here the function sum will return the sum of all the numbers passed in the params:
const sum = a => b => b ? sum(a + b) : a
sum(1)(2)(3)(4)(5)() // 15
function add(a) {
let curry = (b) => {
a += b
return curry;
}
curry[Symbol.toPrimitive] = (hint) => {
return a;
}
return curry
}
console.log(+add(1)(2)(3)(4)(5)); // 15
console.log(+add(6)(6)(6)); // 18
console.log(+add(7)(0)); // 7
console.log(+add(0)); // 0
Here is another functional way using an iterative process
const sum = (num, acc = 0) => {
if !(typeof num === 'number') return acc;
return x => sum(x, acc + num)
}
sum(1)(2)(3)()
and one-line
const sum = (num, acc = 0) => !(typeof num === 'number') ? acc : x => sum(x, acc + num)
sum(1)(2)(3)()
You can make use of the below function
function add(num){
add.sum || (add.sum = 0) // make sure add.sum exists if not assign it to 0
add.sum += num; // increment it
return add.toString = add.valueOf = function(){
var rtn = add.sum; // we save the value
return add.sum = 0, rtn // return it before we reset add.sum to 0
}, add; // return the function
}
Since functions are objects, we can add properties to it, which we are resetting when it's been accessed.
we can also use this easy way.
function sum(a) {
return function(b){
if(b) return sum(a+b);
return a;
}
}
console.log(sum(1)(2)(3)(4)(5)());
To make sum(1) callable as sum(1)(2), it must return a function.
The function can be either called or converted to a number with valueOf.
function sum(a) {
var sum = a;
function f(b) {
sum += b;
return f;
}
f.toString = function() { return sum }
return f
}
function sum(a){
let res = 0;
function getarrSum(arr){
return arr.reduce( (e, sum=0) => { sum += e ; return sum ;} )
}
function calculateSumPerArgument(arguments){
let res = 0;
if(arguments.length >0){
for ( let i = 0 ; i < arguments.length ; i++){
if(Array.isArray(arguments[i])){
res += getarrSum( arguments[i]);
}
else{
res += arguments[i];
}
}
}
return res;
}
res += calculateSumPerArgument(arguments);
return function f(b){
if(b == undefined){
return res;
}
else{
res += calculateSumPerArgument(arguments);
return f;
}
}
}
let add = (a) => {
let sum = a;
funct = function(b) {
sum += b;
return funct;
};
Object.defineProperty(funct, 'valueOf', {
value: function() {
return sum;
}
});
return funct;
};
console.log(+add(1)(2)(3))
After looking over some of the other solutions on here, I would like to provide my two solutions to this problem.
Currying two items using ES6:
const sum = x => y => (y !== undefined ) ? +x + +y : +x
sum(2)(2) // 4
Here we are specifying two parameters, if the second one doesnt exist we just return the first parameter.
For three or more items, it gets a bit trickier; here is my solution. For any additional parameters you can add them in as a third
const sum = x => (y=0) => (...z) => +x + +y + +z.reduce((prev,curr)=>prev+curr,0)
sum(2)()()//2
sum(2)(2)()//4
sum(2)(2)(2)//6
sum(2)(2)(2,2)//8
I hope this helped someone

Calculate Base Factorial

How could I function named unfactorial that takes a number and returns a string representing it's base factorial in the form: n!? This would result in the un-do the factorial operation if one is possible. It should return null if no factorial was possible.
Package
A factorial operation looks like this:
5! = 5 * 4 * 3 * 2 * 1 = 120
Function Output:
unfactorial(120) // '5!'
unfactorial(150) // null
unfactorial(5040) // '7!'
My current Solution
const unfactorial = (num) => {
let d = 1
while (num > 1 && Math.round(num === num)) {
d += 1
num /= d
}
if (num === 1)
return `${d}!`
else return null
}
Here's one way you could do it using an auxiliary recursive function.
Note, it will not work for numbers that are not actual factorials. This is left as an exercise for the asker.
const unfactorial = x => {
const aux = (acc, x) => {
if (x === 1)
return acc - 1
else
return aux(acc + 1, x / acc)
}
return aux(2, x)
}
console.log(unfactorial(120)) // 5
console.log(unfactorial(5040)) // 7
How it works
Starting with the input number x and a counter, acc = 2, successively divide x by acc (then acc + 1, then acc + 2, etc) until x == 1. Then return acc - 1.
Or go bananas using only expressions. You'll probably like this, #Mr.Polywhirl
const U = f => f (f)
const Y = U (h => f => f (x => h (h) (f) (x)))
const unfactorial = Y (f => acc => x =>
x === 1 ? acc - 1 : f (acc + 1) (x / acc)
) (2)
console.log(unfactorial(120)) // 5
console.log(unfactorial(5040)) // 7

Why is my javascript code not behaving as expected when run on console? [duplicate]

I have an entry level question for javascript. When executing the following the result is
false
true
Some numbers are equal
number, number
numbernumbernumber
Why are the first 2 values different?
Why is the first one wrong?
JS:
function sort3(a, b, c)
{
document.getElementById("output").innerHTML =
(typeof a) + (typeof b) + (typeof c);
if(a > b > c) { return [a, b, c];
else if(a > c > b) return [a, c, b];
else if(c > a > b) return [c, a, b];
else if(c > b > a) return [c, b, a];
else if(b > c > a) return [b, c, a];
else if(b > a > c) return [b, a, c];
else return "Some numbers are equal";
}
HTML:
<p id="ex1"></p>
<p id="output"></p>
<script type="text/javascript">
var m = parseFloat(1);
var k = parseFloat(2);
var l = parseFloat(3);
var q = typeof m;
var w = typeof k;
var e = typeof l;
var res1 = (l>k>m) + "</br>";
res1 += (m<k<l) + "</br>";
var res2 = sort3(m,k,l) + "</br>";
var res3 = (typeof m) + ", " + (typeof Number(m))
document.getElementById("ex1").innerHTML = res1 + res2 + res3;
</script>
To do compound comparisons in JavaScript (or any other language syntactically derived from B), you don't do things like
(l>k>m) // <=== Wrong
Instead, if you want to know if l is greater than k and k is greater than m, you use && (the logical "and" operator), like this:
(l>k && k>m)
Details:
Your original expression (l>k>m) breaks down into this:
((l>k)>m)
which means you'll get one of these:
(true>m)
// or
(false>m)
When comparing a boolean to a number, the boolean is coerced to a number, so that becomes in effect:
(1>m)
// or
(0>m)

JavaScript function in a function

I have tried to get this q but without any success...
The task is to build a function by this conditions:
// b('m') -> 'bm'
// b()()('m') -> 'boom'
// b()()()()('m') -> 'boooom'
That is my try:
var b = (a) => {
var counter = 0;
var times = counter += 1;
var d = (a, o, times) => {
var o = 'o'.repeat(times);
return ('b' + o + a);
};
return d();
};
console.log(b('m'));
You need to return a function when the input is not 'm' – returning d () is not returning a function, it's returning the result of a call to d
Here's a way you can do it using an optional parameter with a default value
const b = (a, acc = 'b') =>
a === 'm'
? acc + a
: a => b (a, acc + 'o')
console.log (b ('m'))
console.log (b () ('m'))
console.log (b () () ('m'))
console.log (b () () () ('m'))
And another way using continuation-passing style
const b = (a, k = m => 'b' + m) =>
a === 'm'
? k (a)
: a => b (a, m =>
k ('o' + m))
console.log (b ('m'))
console.log (b () ('m'))
console.log (b () () ('m'))
console.log (b () () () ('m'))
Some people complain about things they don't understand - here's the same function using imperative style
function b (a, acc = 'b')
{
if (a === 'm')
return a
else
return a => b (a, acc + 'o')
}
As another variant of what naomik and NinaScholz proposed, you could avoid the extra optional argument, and use the this context (in ES6) to store a number primitive value that tracks how many 'o' characters to produce:
function b(a) {
return a ? 'b' + 'o'.repeat(+this) + a : b.bind((+this||0)+1);
}
console.log(b('m'));
console.log(b()('m'));
console.log(b()()('m'));
console.log(b()()()('m'));
The string is only composed when b is called with a (truthy) argument: that string is a "b" followed by a number of "o" characters (determined by this) and finally the argument (i.e. "m" in the actual calls). If this is not defined (or is the global object, in non-strict mode), the count of "o" is considered to be 0. This happens when b is called immediately with an argument (no chaining).
When b is called without argument, the function itself is returned, but with a this bound to it that has been increased with 1. NB: so it is not actually the function itself, but a bound variant of it.
You could return use Function#bind and use a temporary this.
function b() {
return arguments.length
? (this.value || 'b') + arguments[0]
: b.bind({ value: (this.value || 'b') + 'o' });
}
console.log(b('m'));
console.log(b()('m'));
console.log(b()()('m'));
console.log(b()()()('m'));
function b must return itself binded to number + 1 if it was called with no params. and return a string bo.(n times).om.
b is initially binded to 0.
let b = (function boom(number, value) {
if (value === 'm') {
return 'b' + 'o'.repeat(number) + 'm';
}
else {
return boom.bind(null, number + 1);
}
}).bind(null, 0); // number value is initialized to 0
console.log(b()()('m')); // boom

Categories