2022-12-07 01:21:05 +00:00
|
|
|
import {configDependency} from '../core/Config.js'
|
2022-12-21 05:18:42 +00:00
|
|
|
import {BBinary, Dependency, ImpType} from '../core/Dispatcher.js'
|
|
|
|
import type {Complex} from '../Complex/type.js'
|
2022-12-07 01:21:05 +00:00
|
|
|
|
2022-12-21 05:18:42 +00:00
|
|
|
declare module "./type" {
|
|
|
|
interface NumbersReturn<Params> {
|
|
|
|
// This description loses information: some subtypes like NumInt or
|
|
|
|
// Positive are closed under addition, but this says that the result
|
|
|
|
// of add is just a number, not still of the reduced type
|
|
|
|
add: Params extends BBinary<number> ? number : never
|
|
|
|
// Whereas this one would preserve information, but would lie
|
|
|
|
// because it claims all subtypes of number are closed under addition,
|
|
|
|
// which is not true for `1 | 2 | 3`, for example.
|
|
|
|
// add: Params extends BBinary<infer B>
|
|
|
|
// ? B extends number ? B : never
|
|
|
|
// : never
|
|
|
|
//
|
|
|
|
// Not sure how this will need to go when we introduce NumInt.
|
|
|
|
unaryMinus: Params extends [number] ? number : never
|
|
|
|
subtract: Params extends BBinary<number> ? number : never
|
|
|
|
multiply: Params extends BBinary<number> ? number : never
|
|
|
|
divide: Params extends BBinary<number> ? number : never
|
|
|
|
// Best we can do for sqrt at compile time, since actual return
|
|
|
|
// type depends on config. Not sure how this will play out
|
|
|
|
// when we make a number-only bundle, but at least the import type
|
|
|
|
// above for Complex<> does not lead to any emitted JavaScript.
|
|
|
|
sqrt: Params extends [number] ? (number | Complex<number>) : never
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const add: ImpType<'add', [number, number]> = (a, b) => a + b
|
|
|
|
export const unaryMinus: ImpType<'unaryMinus', [number]> = a => -a
|
|
|
|
export const subtract: ImpType<'subtract', [number, number]> = (a, b) => a - b
|
|
|
|
export const multiply: ImpType<'multiply', [number, number]> = (a, b) => a * b
|
|
|
|
export const divide: ImpType<'divide', [number, number]> = (a, b) => a / b
|
2022-12-07 01:21:05 +00:00
|
|
|
export const sqrt =
|
|
|
|
(dep: configDependency
|
2022-12-21 05:18:42 +00:00
|
|
|
& Dependency<'complex', [number, number]>): ImpType<'sqrt', [number]> => {
|
2022-12-07 01:21:05 +00:00
|
|
|
if (dep.config.predictable || !dep.complex) {
|
2022-12-21 05:18:42 +00:00
|
|
|
return a => isNaN(a) ? NaN : Math.sqrt(a)
|
2022-12-07 01:21:05 +00:00
|
|
|
}
|
2022-12-21 05:18:42 +00:00
|
|
|
return a => {
|
2022-12-07 01:21:05 +00:00
|
|
|
if (isNaN(a)) return NaN
|
|
|
|
if (a >= 0) return Math.sqrt(a)
|
|
|
|
return dep.complex(0, Math.sqrt(unaryMinus(a)))
|
|
|
|
}
|
|
|
|
}
|