UNPKG

1.28 kBJavaScriptView Raw
1import { deepMap } from '../../utils/collection'
2import { factory } from '../../utils/factory'
3
4const name = 'factorial'
5const dependencies = ['typed', 'gamma']
6
7export const createFactorial = /* #__PURE__ */ factory(name, dependencies, ({ typed, gamma }) => {
8 /**
9 * Compute the factorial of a value
10 *
11 * Factorial only supports an integer value as argument.
12 * For matrices, the function is evaluated element wise.
13 *
14 * Syntax:
15 *
16 * math.factorial(n)
17 *
18 * Examples:
19 *
20 * math.factorial(5) // returns 120
21 * math.factorial(3) // returns 6
22 *
23 * See also:
24 *
25 * combinations, combinationsWithRep, gamma, permutations
26 *
27 * @param {number | BigNumber | Array | Matrix} n An integer number
28 * @return {number | BigNumber | Array | Matrix} The factorial of `n`
29 */
30 const factorial = typed(name, {
31 number: function (n) {
32 if (n < 0) {
33 throw new Error('Value must be non-negative')
34 }
35
36 return gamma(n + 1)
37 },
38
39 BigNumber: function (n) {
40 if (n.isNegative()) {
41 throw new Error('Value must be non-negative')
42 }
43
44 return gamma(n.plus(1))
45 },
46
47 'Array | Matrix': function (n) {
48 return deepMap(n, factorial)
49 }
50 })
51
52 return factorial
53})