John Conor Cosnett - 1 year ago 43

Javascript Question

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

Answer

You can't do it this 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
```

Source (Stackoverflow)