feat: Add complex numbers

No negation (and therefore no subtraction) since that needs self-reference.
This commit is contained in:
Glen Whitney 2022-07-19 09:52:16 -07:00
parent b59a8c2ca9
commit b82336e590
7 changed files with 71 additions and 0 deletions

14
complex/Complex.mjs Normal file
View file

@ -0,0 +1,14 @@
import typed from 'typed-function'
/* Use a plain object with keys re and im for a complex */
typed.addType({
name: 'Complex',
test: z => z && typeof z === 'object' && 're' in z && 'im' in z
})
typed.addConversion({
from: 'number',
to: 'Complex',
convert: x => ({re: x, im: 0})
})

12
complex/add.mjs Normal file
View file

@ -0,0 +1,12 @@
import './Complex.mjs'
export const add = {
'...Complex': [[], addends => {
const sum = {re: 0, im: 0}
addends.forEach(addend => {
sum.re += addend.re
sum.im += addend.im
})
return sum
}]
}

2
complex/all.mjs Normal file
View file

@ -0,0 +1,2 @@
export {complex} from './complex.mjs'
export {add} from './add.mjs'

6
complex/complex.mjs Normal file
View file

@ -0,0 +1,6 @@
import './Complex.mjs'
export const complex = {
'number, number': [[], (x, y) => ({re: x, im: y})],
Complex: [[], z => z]
}