Conor Cosnett
Conor Cosnett

Reputation: 1306

How to build a function with multiple fat arrows clauses in javascript?

I am coming to Javascript from a functional background.

I am imagining something like this to compute the factorial of 3:

var Function1 =    
{
  (0) => 1,
  (1) => 1,
  (n) => n*Function1(n-1)
}

document.write(Function1(3),"<br/>")

but it doesn't work.

Is there something similar to my example in javascript that computes 6 using fat arrow notation?

Upvotes: 2

Views: 112

Answers (2)

kernel
kernel

Reputation: 3743

You can't do it in the descriptive/declarative way in JS, but you can listen to the value of the parameter and react accordingly:

var Function1 = (n) => {
  if (n === 0) return 1;
  if (n === 1) return 1;
  return Function1(n-1)*n;
}
document.write(Function1(3),"<br/>"); // 6

Another way would be to return a curried function:

var Function1 = (n) => {
  if (n === 0) return () => 1;
  if (n === 1) return () => 1;
  return () => Function1(n-1)()*n;
}
document.write(Function1(3)(),"<br/>"); // 6

Mind the second function call here Function1(3)().

Your example could be shortened a bit with a ternary operator, but it works against maintainability and readability:

var Function1 = (n) => [0, 1].includes(n) ? 1 : Function1(n-1)*n;
document.write(Function1(3),"<br/>"); // 6

Upvotes: 4

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Simplified "one-line" alternative using Number constructor:

var Function1 = (n) => { return Number(n === 0 || n === 1) || Function1(n-1)*n; };

console.log(Function1(0));  // 1
console.log(Function1(1));  // 1
console.log(Function1(4));  // 24

Upvotes: 1

Related Questions