feat: Add complex numbers

With just the operations we have for numbers, and overall tests.
This commit is contained in:
Glen Whitney 2022-03-25 01:54:20 -07:00
parent 536656bfe8
commit 32bc9ca515
8 changed files with 80 additions and 7 deletions

16
complex/add.js Normal file
View file

@ -0,0 +1,16 @@
import { anyComplex } from './complex.js'
export default function create(pmath) {
const complex = pmath('complex')
return pmath('add', [anyComplex, // naive, but this is just a P-o-C
(...addends) => {
let sum = complex(addends[0])
for (let i = 1; i < addends.length; ++i) {
const addend = complex(addends[i])
sum.re += addend.re
sum.im += addend.im
}
return sum
}])
}

12
complex/all.js Normal file
View file

@ -0,0 +1,12 @@
import createComplex from './complex.js'
import createAdd from './add.js'
import createNegate from './negate.js'
import createSubtract from '../generic/subtract.js'
export default function create(pmath) {
createComplex(pmath)
createAdd(pmath)
createNegate(pmath)
createSubtract(pmath)
// not sure if there's anything reasonable to return here
}

21
complex/complex.js Normal file
View file

@ -0,0 +1,21 @@
/* Use a plain object with keys re and im for a complex */
export function isComplex(z) {
return z && typeof z === 'object' && 're' in z && 'im' in z
}
export function anyComplex(args) {
for (let i = 0; i < args.length; ++i) {
if (isComplex(args[i])) return true
}
return false
}
export default function create(pmath) {
const number = pmath('number')
return pmath('complex', [
[args => args.length == 2, (x,y) => ({re: number(x), im: number(y)})],
[args => args.length == 1 && isComplex(args[0]), z => z],
[args => args.length == 1, x => ({re: number(x), im: 0})]
])
}

6
complex/negate.js Normal file
View file

@ -0,0 +1,6 @@
import { isComplex } from './complex.js'
export default function create(pmath) {
return pmath('negate', [args => args.length == 1 && isComplex(args[0]),
z => ({re: -z.re, im: -z.im})])
}