feat: Return type annotations #53

Merged
glen merged 15 commits from return_types into main 2022-08-30 19:36:44 +00:00
4 changed files with 17 additions and 7 deletions
Showing only changes of commit be9794fd4c - Show all commits

View File

@ -1,11 +1,13 @@
/* Note this is not a good algorithm for computing binomial coefficients, import Returns from '../core/Returns.mjs'
/* Note this is _not_ a good algorithm for computing binomial coefficients,
* it's just for demonstration purposes * it's just for demonstration purposes
*/ */
export const choose = { export const choose = {
'NumInt,NumInt': ({factorial}) => (n,k) => Number( 'NumInt,NumInt': ({factorial}) => Returns(
factorial(n) / (factorial(k)*factorial(n-k))), 'NumInt', (n,k) => Number(factorial(n) / (factorial(k)*factorial(n-k)))),
'bigint,bigint': ({ 'bigint,bigint': ({
factorial factorial
}) => (n,k) => factorial(n) / (factorial(k)*factorial(n-k)) }) => Returns('bigint', (n,k) => factorial(n) / (factorial(k)*factorial(n-k)))
} }

View File

@ -1,8 +1,15 @@
export function factorial(n) { import Returns from '../core/Returns.mjs'
/* Plain functions are OK, too, and they can be decorated with a return type
* just like an implementation.
*/
const factorial = Returns('bigint', function factorial(n) {
n = BigInt(n) n = BigInt(n)
let prod = 1n let prod = 1n
for (let i = n; i > 1n; --i) { for (let i = n; i > 1n; --i) {
prod *= i prod *= i
} }
return prod return prod
} })
export {factorial}

View File

@ -25,7 +25,6 @@ export const floor = {
// OK to include a type totally not in Pocomath yet, it'll never be // OK to include a type totally not in Pocomath yet, it'll never be
// activated. // activated.
// Fraction: ({quotient}) => f => quotient(f.n, f.d), // oops have that now
BigNumber: ({ BigNumber: ({
'round(BigNumber)': rnd, 'round(BigNumber)': rnd,
'equal(BigNumber,BigNumber)': eq 'equal(BigNumber,BigNumber)': eq

View File

@ -63,6 +63,8 @@ describe('The default full pocomath instance "math"', () => {
assert.strictEqual(math.returnTypeOf('isZero', 'NumInt'), 'boolean') assert.strictEqual(math.returnTypeOf('isZero', 'NumInt'), 'boolean')
assert.strictEqual( assert.strictEqual(
math.returnTypeOf('roundquotient', 'NumInt,number'), 'NumInt') math.returnTypeOf('roundquotient', 'NumInt,number'), 'NumInt')
assert.strictEqual(
math.returnTypeOf('factorial', 'NumInt'), 'bigint')
}) })
it('can subtract numbers', () => { it('can subtract numbers', () => {