Calling a value of a ternary operator in 1 line

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top