diff --git a/README.md b/README.md index e84ab3d..2f9ad4c 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ $ yarn test - [Subtract](src/subtract/index.d.ts) - subtracts two numbers. - [Multiply](src/multiply/index.d.ts) - multiplies two numbers. - [Divide](src/divide/index.d.ts) - divides two numbers. + - [Power](src/power/index.d.ts) - computes the given base taken to the power of the given exponent. - [Greater than or equal](src/gte/index.d.ts) - checks if a value is greater than or equal to another value. - [Less than or equal](src/lte/index.d.ts) - checks if a value is less than or equal to another value. - [Max](src/max/index.d.ts) - computes the maximum value of an array. diff --git a/src/power/index.d.ts b/src/power/index.d.ts new file mode 100644 index 0000000..743de32 --- /dev/null +++ b/src/power/index.d.ts @@ -0,0 +1,32 @@ +import { Multiply, Dec, Cast } from '..'; + +// Power two numbers: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow +// +type S = Power<2, 3>; // 8 +// +// This type uses recursive (and not officially supported) type alias, see more: +// https://github.com/microsoft/TypeScript/issues/26223#issuecomment-513187373. +export type Power< + // The Base. + A extends number, + // The Exponent used to raise the Base. + B extends number + > = { + // If A is 0: return 0 + // If B is 0: return 1 + zero: 0; + one: 1; + // If they're both not 1s or 0s, we call the recursion again, like this: + // + // Multiply>> + // + // We multiply the value of the first number (A) to the result of calling Multiply + // again in which we decrease B's value by 1. This means that we call Multiply + // B times. + // + // Computation is split into multiple steps with `infer`, see more: + // https://github.com/pirix-gh/medium/blob/master/types-curry-ramda/src/index.ts#L17. + next: Power> extends infer G // Assign result to `G` + ? Multiply> + : never; +}[B extends 0 ? 'one' : A extends 0 ? 'zero' : A extends 1 ? 'one' : 'next']; diff --git a/src/power/index.test-d.ts b/src/power/index.test-d.ts new file mode 100644 index 0000000..61e3146 --- /dev/null +++ b/src/power/index.test-d.ts @@ -0,0 +1,12 @@ +import { expectType } from 'tsd'; +import { Power } from '.'; + +expectType>(8); +expectType>(9); +expectType>(1); +expectType>(0); +expectType>(1); +expectType>(1); +expectType>(1); +expectType>(4); +expectType>(this as never);