Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Recursive Function Currying and Arrow Functions

Tags:

javascript

This is fine and works:

const power = (x,n) => {
  if (n === 0) return 1;
  return x * power(x, n - 1);
}

power(4,3) 64

But trying to do this as experiment - does not work gives NaN Do not understand why:

node .editor // Entering editor mode (Ctrl+D to finish, Ctrl+C to cancel)

const power = x => {
  return n => {
    if (n === 0) return 1;
    return x * power(x, n - 1);
  }
}

let t = power(4) t(3) NaN

like image 648
Mark Koban Avatar asked Jul 04 '26 02:07

Mark Koban


2 Answers

You haven't converted the recursive call in the curried version to curried form. power(x, n - 1) is essentially the same as power(x) because power only accepts one argument, and this is a function, so not unreasonably becomes NaN when you try to multiply it by a number.

Rewrite it like this instead:

const power = x => {
  return n => {
    if (n === 0) return 1;
    return x * power(x)(n - 1);
  }
};

console.log('4^3 = ', power(4)(3));     // 64
console.log('2^10 = ', power(2)(10));   // 1024
console.log('5^4 = ', power(5)(4));     // 625
console.log('3^4 = ', power(3)(4));     // 81
like image 101
Robin Zigmond Avatar answered Jul 05 '26 15:07

Robin Zigmond


You could store the nested function and return the function and use this function for another call with only the changed n.

const
    power = x => {
        const
            fn = n => n === 0
                ? 1
                : x * fn(n - 1);

        return fn;
    };

console.log(power(4)(3));
like image 45
Nina Scholz Avatar answered Jul 05 '26 16:07

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!