@arcosmos/astronomy 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +227 -2
- package/dist/angles.d.ts +51 -0
- package/dist/angles.d.ts.map +1 -0
- package/dist/angles.js +261 -0
- package/dist/angles.js.map +1 -0
- package/dist/constants.d.ts +35 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +44 -0
- package/dist/constants.js.map +1 -0
- package/dist/coordinates.d.ts +213 -0
- package/dist/coordinates.d.ts.map +1 -0
- package/dist/coordinates.js +474 -0
- package/dist/coordinates.js.map +1 -0
- package/dist/distance.d.ts +26 -0
- package/dist/distance.d.ts.map +1 -0
- package/dist/distance.js +54 -0
- package/dist/distance.js.map +1 -0
- package/dist/errors.d.ts +24 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/kinds.d.ts +86 -0
- package/dist/kinds.d.ts.map +1 -0
- package/dist/kinds.js +29 -0
- package/dist/kinds.js.map +1 -0
- package/dist/parse-unit.d.ts +11 -0
- package/dist/parse-unit.d.ts.map +1 -0
- package/dist/parse-unit.js +222 -0
- package/dist/parse-unit.js.map +1 -0
- package/dist/quantity.d.ts +150 -0
- package/dist/quantity.d.ts.map +1 -0
- package/dist/quantity.js +452 -0
- package/dist/quantity.js.map +1 -0
- package/dist/rounding.d.ts +18 -0
- package/dist/rounding.d.ts.map +1 -0
- package/dist/rounding.js +35 -0
- package/dist/rounding.js.map +1 -0
- package/dist/time.d.ts +100 -0
- package/dist/time.d.ts.map +1 -0
- package/dist/time.js +448 -0
- package/dist/time.js.map +1 -0
- package/dist/units.d.ts +394 -0
- package/dist/units.d.ts.map +1 -0
- package/dist/units.js +353 -0
- package/dist/units.js.map +1 -0
- package/package.json +44 -3
- package/src/angles.ts +286 -0
- package/src/constants.ts +51 -0
- package/src/coordinates.ts +591 -0
- package/src/distance.ts +58 -0
- package/src/errors.ts +27 -0
- package/src/index.ts +27 -0
- package/src/kinds.ts +110 -0
- package/src/parse-unit.ts +230 -0
- package/src/quantity.ts +539 -0
- package/src/rounding.ts +33 -0
- package/src/time.ts +511 -0
- package/src/units.ts +445 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// @arcosmos/astronomy: units and quantities with uncertainties, angles, directions on the sky
|
|
2
|
+
// in Astropy's frames with their space motion, and times in Astropy's scales, built on
|
|
3
|
+
// @arcosmos/erfa. No key, no network: it runs the same in a browser, Node, Deno, Bun or a Worker.
|
|
4
|
+
export { type AngleUnit, type FormatAngleOptions, formatAngle, parseAngle } from './angles.ts'
|
|
5
|
+
export * from './constants.ts'
|
|
6
|
+
export { distanceFromParallax, distanceModulus, distanceModulusPc, parallaxDistancePc } from './distance.ts'
|
|
7
|
+
export type { Mat3, Vec3 } from '@arcosmos/erfa'
|
|
8
|
+
export {
|
|
9
|
+
type AngleInput, type Equinox, FRAME_COMPONENTS, FRAME_PROPER_MOTIONS, type FrameName, type MotionInput, SkyCoord,
|
|
10
|
+
type SkyCoordInput, type SkyCoordStyle, type StarAt, frameRotation, moveStar, skyCoord,
|
|
11
|
+
} from './coordinates.ts'
|
|
12
|
+
export { QuantityParseError, TimeParseError, UncertaintyError, UnitConversionError, UnitParseError } from './errors.ts'
|
|
13
|
+
export {
|
|
14
|
+
COMPOUND_KINDS, type ConvertibleKind, type KindOf, LOG_KINDS, type SymbolOf, type TargetKind, type UnitTarget, type UnitText,
|
|
15
|
+
} from './kinds.ts'
|
|
16
|
+
export { parseUnit, unit } from './parse-unit.ts'
|
|
17
|
+
export {
|
|
18
|
+
type AsymmetricUncertainty, type EllipseUncertainty, type EllipseUncertaintyJSON, type KindOfQuantity, type Limit,
|
|
19
|
+
type MeasurementLike, type PercentileUncertainty, Quantity, type QuantityJSON,
|
|
20
|
+
type QuantityOptions, type SymmetricUncertainty, type SymmetrizeRule, type Uncertainty, type UncertaintyJSON,
|
|
21
|
+
fromMeasurement, parseQuantity, q,
|
|
22
|
+
} from './quantity.ts'
|
|
23
|
+
export { roundToSignificant, roundToUncertainty } from './rounding.ts'
|
|
24
|
+
export { Time, type TimeFormat, type TimeInput, type TimeOptions, type TimeScale, time } from './time.ts'
|
|
25
|
+
export {
|
|
26
|
+
BASE_UNITS, DEFINITIONS, DIMENSIONLESS, type Kind, type KnownKind, type LinearKind, type LogPart, PREFIXES, Unit,
|
|
27
|
+
} from './units.ts'
|
package/src/kinds.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// The kind of a unit, as the type system sees it. `q(10, "ly")` is a Quantity<"length">, so
|
|
2
|
+
// adding a time to it, or converting it to km/s, is a compile error. The type system knows each
|
|
3
|
+
// symbol, every prefixed symbol, and the common compound units below. Any other unit still
|
|
4
|
+
// works at run time, typed by its kind only as a string; `unit(text, kind)` or Quantity.as
|
|
5
|
+
// names the kind, checked when it runs.
|
|
6
|
+
import type { DEFINITIONS, Kind, LinearKind, PREFIXES, Unit } from './units.ts'
|
|
7
|
+
|
|
8
|
+
type Definitions = typeof DEFINITIONS
|
|
9
|
+
type Canonical = keyof Definitions
|
|
10
|
+
|
|
11
|
+
/** Each canonical symbol and alias, with its kind. */
|
|
12
|
+
type SymbolKinds = { [S in Canonical]: Definitions[S]['kind'] } & {
|
|
13
|
+
[S in Canonical as Definitions[S] extends { aliases: readonly (infer A extends string)[] } ? A : never]:
|
|
14
|
+
Definitions[S]['kind']
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type Prefix = keyof typeof PREFIXES
|
|
18
|
+
type Prefixable = { [S in Canonical]: Definitions[S] extends { prefixes: true } ? S : never }[Canonical]
|
|
19
|
+
|
|
20
|
+
/** Logarithmic symbols. */
|
|
21
|
+
export const LOG_KINDS = { mag: 'magnitude', dex: 'dex' } as const
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Compound units written often enough that the type system should know their kind. Written
|
|
25
|
+
* exactly as here; the same unit written another way is typed as any Kind.
|
|
26
|
+
*/
|
|
27
|
+
export const COMPOUND_KINDS = {
|
|
28
|
+
'': 'dimensionless',
|
|
29
|
+
'km/s': 'speed',
|
|
30
|
+
'm/s': 'speed',
|
|
31
|
+
'cm/s': 'speed',
|
|
32
|
+
'au/d': 'speed',
|
|
33
|
+
'mas/yr': 'angular speed',
|
|
34
|
+
'arcsec/yr': 'angular speed',
|
|
35
|
+
'deg/d': 'angular speed',
|
|
36
|
+
'cm/s^2': 'acceleration',
|
|
37
|
+
'm/s^2': 'acceleration',
|
|
38
|
+
'W/m^2': 'energy flux',
|
|
39
|
+
'erg/(cm^2 s)': 'energy flux',
|
|
40
|
+
'erg/s': 'power',
|
|
41
|
+
'g/cm^3': 'mass density',
|
|
42
|
+
'kg/m^3': 'mass density',
|
|
43
|
+
'deg^2': 'solid angle',
|
|
44
|
+
'arcmin^2': 'solid angle',
|
|
45
|
+
'arcsec^2': 'solid angle',
|
|
46
|
+
'log10(L_sun)': 'log(power)',
|
|
47
|
+
'log10(cm/s^2)': 'log(acceleration)',
|
|
48
|
+
} as const satisfies Record<string, Kind>
|
|
49
|
+
|
|
50
|
+
type LogKinds = typeof LOG_KINDS
|
|
51
|
+
type CompoundKinds = typeof COMPOUND_KINDS
|
|
52
|
+
|
|
53
|
+
/** The kinds a prefixed symbol could have: "km" is "length"; never when no prefix fits. */
|
|
54
|
+
type PrefixedKind<S extends string, P extends Prefix = Prefix> = P extends Prefix
|
|
55
|
+
? S extends `${P}${infer B extends Prefixable}` ? SymbolKinds[B] : never
|
|
56
|
+
: never
|
|
57
|
+
|
|
58
|
+
/** The kind of log10 of a unit of kind K: "log(power)" for log10(W). */
|
|
59
|
+
type LogKindOf<K> = [K] extends [LinearKind] ? `log(${K & LinearKind})` : Kind
|
|
60
|
+
|
|
61
|
+
/** The kind of a unit written as S, or Kind when the type system can't tell. */
|
|
62
|
+
export type KindOf<S extends string> = string extends S ? Kind
|
|
63
|
+
: S extends keyof SymbolKinds ? SymbolKinds[S]
|
|
64
|
+
: S extends keyof LogKinds ? LogKinds[S]
|
|
65
|
+
: S extends keyof CompoundKinds ? CompoundKinds[S]
|
|
66
|
+
: S extends `log10(${infer X})` ? LogKindOf<KindOf<X>>
|
|
67
|
+
: [PrefixedKind<S>] extends [never] ? Kind
|
|
68
|
+
: PrefixedKind<S>
|
|
69
|
+
|
|
70
|
+
/** Every unit the type system knows, with its kind. */
|
|
71
|
+
type KnownSymbols = keyof SymbolKinds | `${Prefix}${Prefixable}` | keyof LogKinds | keyof CompoundKinds
|
|
72
|
+
|
|
73
|
+
/** The units of kind K the type system knows, for completion and checking: SymbolOf<"length"> includes "pc" and "km". */
|
|
74
|
+
export type SymbolOf<K extends string> =
|
|
75
|
+
| { [S in keyof SymbolKinds]: SymbolKinds[S] extends K ? S : never }[keyof SymbolKinds]
|
|
76
|
+
| { [B in Prefixable]: SymbolKinds[B] extends K ? `${Prefix}${B}` : never }[Prefixable]
|
|
77
|
+
| { [S in keyof LogKinds]: LogKinds[S] extends K ? S : never }[keyof LogKinds]
|
|
78
|
+
| { [S in keyof CompoundKinds]: CompoundKinds[S] extends K ? S : never }[keyof CompoundKinds]
|
|
79
|
+
| (K extends `log(${infer L extends LinearKind})` ? `log10(${SymbolOf<L>})` : never)
|
|
80
|
+
|
|
81
|
+
/** The kinds a quantity of kind K converts to: its own, and magnitudes and dex to each other. */
|
|
82
|
+
export type ConvertibleKind<K extends string> =
|
|
83
|
+
| K
|
|
84
|
+
| (K extends 'magnitude' ? 'dex' : never)
|
|
85
|
+
| (K extends 'dex' ? 'magnitude' : never)
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The kinds a quantity of kind K converts to with `to`: ConvertibleKind's, and between log10 of
|
|
89
|
+
* a unit and the unit, and mag and dex and a plain number.
|
|
90
|
+
*/
|
|
91
|
+
export type ConversionKind<K extends string> =
|
|
92
|
+
| ConvertibleKind<K>
|
|
93
|
+
| (K extends `log(${infer L extends LinearKind})` ? L : never)
|
|
94
|
+
| (K extends Exclude<LinearKind, 'dimensionless'> ? `log(${K})` : never)
|
|
95
|
+
| (K extends 'magnitude' | 'dex' ? 'dimensionless' : never)
|
|
96
|
+
| (K extends 'dimensionless' ? 'magnitude' | 'dex' : never)
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* What a unit argument of kind K may be: a known unit of that kind, written out, for a known
|
|
100
|
+
* kind; any text for a kind the type system can't tell.
|
|
101
|
+
*/
|
|
102
|
+
export type UnitText<K extends string> = string extends K ? string : SymbolOf<K>
|
|
103
|
+
|
|
104
|
+
/** A unit a quantity of kind K converts to, as text or a Unit. */
|
|
105
|
+
export type UnitTarget<K extends string> = UnitText<ConversionKind<K>> | Unit<ConversionKind<K>>
|
|
106
|
+
|
|
107
|
+
/** The kind of a unit given as text or as a Unit. */
|
|
108
|
+
export type TargetKind<T> = T extends Unit<infer K> ? K : T extends string ? KindOf<T> : Kind
|
|
109
|
+
|
|
110
|
+
export type { KnownSymbols }
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// Reading units from text: "km/s", "mas/yr", "erg/(cm^2 s)", "m s-1", "log10(cm/s^2)".
|
|
2
|
+
//
|
|
3
|
+
// Symbols are multiplied by a space or `*`, and divided by `/`. A power follows `^` or `**`,
|
|
4
|
+
// or is written straight after the symbol ("m2", "s-1"), and may be a fraction: "m^(1/2)",
|
|
5
|
+
// "m^0.5" (written back as a fraction). After a `/`, a product needs parentheses: "W/(m^2 Hz)", or "W/m^2/Hz". Read either
|
|
6
|
+
// way, "W/m^2 Hz" is a guess, so it's an error rather than a choice made silently.
|
|
7
|
+
//
|
|
8
|
+
// mag and dex are logarithmic, and so is log10(X), Astropy's dex(X) (also read here). A
|
|
9
|
+
// logarithmic unit can't be part of a product.
|
|
10
|
+
import { UnitParseError } from './errors.ts'
|
|
11
|
+
import type { KindOf } from './kinds.ts'
|
|
12
|
+
import { DIMENSIONLESS, type Kind, REGISTRY, Unit, symbolUnit } from './units.ts'
|
|
13
|
+
|
|
14
|
+
type Token =
|
|
15
|
+
| { readonly type: 'symbol'; readonly text: string; readonly power: number | null }
|
|
16
|
+
| { readonly type: 'number'; readonly text: string }
|
|
17
|
+
| { readonly type: 'log' }
|
|
18
|
+
| { readonly type: '(' | ')' | '/' | '*' | '^' | ' ' }
|
|
19
|
+
|
|
20
|
+
const SYMBOL = /^[A-Za-z_µμ]+/
|
|
21
|
+
const ATTACHED_POWER = /^[-+]?\d+(?![.\d])/
|
|
22
|
+
const NUMBER = /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?/
|
|
23
|
+
|
|
24
|
+
function tokenize(text: string): Token[] {
|
|
25
|
+
const tokens: Token[] = []
|
|
26
|
+
let rest = text
|
|
27
|
+
while (rest.length) {
|
|
28
|
+
const c = rest[0]
|
|
29
|
+
if (/^\s/.test(rest)) {
|
|
30
|
+
rest = rest.replace(/^\s+/, '')
|
|
31
|
+
tokens.push({ type: ' ' })
|
|
32
|
+
} else if (rest.startsWith('**')) {
|
|
33
|
+
tokens.push({ type: '^' })
|
|
34
|
+
rest = rest.slice(2)
|
|
35
|
+
} else if (c === '(' || c === ')' || c === '/' || c === '*' || c === '^') {
|
|
36
|
+
tokens.push({ type: c })
|
|
37
|
+
rest = rest.slice(1)
|
|
38
|
+
} else if (/^(?:log10|dex)\s*\(/.test(rest)) {
|
|
39
|
+
tokens.push({ type: 'log' })
|
|
40
|
+
rest = rest.replace(/^(?:log10|dex)\s*/, '')
|
|
41
|
+
} else {
|
|
42
|
+
const symbol = SYMBOL.exec(rest)?.[0]
|
|
43
|
+
if (symbol) {
|
|
44
|
+
rest = rest.slice(symbol.length)
|
|
45
|
+
const power = ATTACHED_POWER.exec(rest)?.[0]
|
|
46
|
+
if (power) rest = rest.slice(power.length)
|
|
47
|
+
tokens.push({ type: 'symbol', text: symbol.replace(/[µμ]/g, 'u'), power: power ? Number(power) : null })
|
|
48
|
+
continue
|
|
49
|
+
}
|
|
50
|
+
const number = NUMBER.exec(rest)?.[0]
|
|
51
|
+
if (!number) throw new UnitParseError(`Unexpected "${c}" in the unit "${text}"`)
|
|
52
|
+
tokens.push({ type: 'number', text: number })
|
|
53
|
+
rest = rest.slice(number.length)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
// A space is a product only between two factors: drop it at either end and around operators.
|
|
57
|
+
return tokens.filter((token, i) => {
|
|
58
|
+
if (token.type !== ' ') return true
|
|
59
|
+
const before = tokens[i - 1]?.type
|
|
60
|
+
const after = tokens[i + 1]?.type
|
|
61
|
+
const operand = (t: Token['type'] | undefined) => t === 'symbol' || t === 'number' || t === 'log'
|
|
62
|
+
return (before === ')' || operand(before)) && (after === '(' || operand(after))
|
|
63
|
+
}).map((token): Token => (token.type === ' ' ? { type: '*' } : token))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
class Parser {
|
|
67
|
+
private i = 0
|
|
68
|
+
private readonly tokens: Token[]
|
|
69
|
+
private readonly text: string
|
|
70
|
+
|
|
71
|
+
constructor(tokens: Token[], text: string) {
|
|
72
|
+
this.tokens = tokens
|
|
73
|
+
this.text = text
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
parse(): Unit {
|
|
77
|
+
if (this.tokens.length === 0) return DIMENSIONLESS
|
|
78
|
+
const unit = this.expression(true)
|
|
79
|
+
if (this.i < this.tokens.length) throw this.error(`Unexpected "${this.describe(this.tokens[this.i])}"`)
|
|
80
|
+
return unit
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A product, then any number of `/ factor`. */
|
|
84
|
+
private expression(top: boolean): Unit {
|
|
85
|
+
let unit = this.product(top)
|
|
86
|
+
while (this.peek()?.type === '/') {
|
|
87
|
+
this.i++
|
|
88
|
+
unit = this.combine(unit, this.factor(false), 'div')
|
|
89
|
+
if (this.peek()?.type === '*') {
|
|
90
|
+
throw this.error('After "/", put a product in parentheses: write "W/(m^2 Hz)" or "W/m^2/Hz"')
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return unit
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private product(top: boolean): Unit {
|
|
97
|
+
let unit = this.factor(top)
|
|
98
|
+
while (this.peek()?.type === '*') {
|
|
99
|
+
this.i++
|
|
100
|
+
unit = this.combine(unit, this.factor(false), 'times')
|
|
101
|
+
}
|
|
102
|
+
return unit
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** An atom and its power. A logarithmic unit is allowed only where it is the whole unit. */
|
|
106
|
+
private factor(top: boolean): Unit {
|
|
107
|
+
const token = this.next()
|
|
108
|
+
let unit: Unit
|
|
109
|
+
if (token?.type === 'symbol') {
|
|
110
|
+
unit = this.symbol(token.text)
|
|
111
|
+
if (token.power !== null) unit = this.power(unit, token.power)
|
|
112
|
+
} else if (token?.type === 'number') {
|
|
113
|
+
// Only the 1 of "1/s", or a 1 alone: "1 pc" would be a value misread as part of the unit.
|
|
114
|
+
if (Number(token.text) !== 1 || !(this.peek()?.type === '/' || (top && this.atEnd()))) {
|
|
115
|
+
throw this.error(`A number in a unit can only be the 1 of "1/s", not "${token.text}" here`)
|
|
116
|
+
}
|
|
117
|
+
unit = DIMENSIONLESS
|
|
118
|
+
} else if (token?.type === 'log') {
|
|
119
|
+
this.expect('(')
|
|
120
|
+
const physical = this.expression(false)
|
|
121
|
+
this.expect(')')
|
|
122
|
+
unit = Unit.logarithmic('dex', physical)
|
|
123
|
+
} else if (token?.type === '(') {
|
|
124
|
+
unit = this.expression(false)
|
|
125
|
+
this.expect(')')
|
|
126
|
+
} else {
|
|
127
|
+
throw this.error(token ? `Unexpected "${this.describe(token)}"` : 'The unit ends too soon')
|
|
128
|
+
}
|
|
129
|
+
if (this.peek()?.type === '^') {
|
|
130
|
+
this.i++
|
|
131
|
+
unit = this.power(unit, this.exponent())
|
|
132
|
+
}
|
|
133
|
+
if (unit.isLogarithmic && !(top && this.atEnd())) {
|
|
134
|
+
throw this.error(`${unit} is logarithmic and can't be multiplied, divided or raised to a power`)
|
|
135
|
+
}
|
|
136
|
+
return unit
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private symbol(text: string): Unit {
|
|
140
|
+
if (text === 'mag' || text === 'dex') return Unit.logarithmic(text, DIMENSIONLESS)
|
|
141
|
+
const entry = REGISTRY.get(text)
|
|
142
|
+
if (!entry) throw this.error(`Unknown unit "${text}"`)
|
|
143
|
+
return symbolUnit(text, entry)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** A number, signed, or a fraction in parentheses: "2", "-1", "0.5", "(1/2)", "(-3/2)". */
|
|
147
|
+
private exponent(): number {
|
|
148
|
+
const token = this.next()
|
|
149
|
+
if (token?.type === 'number') return Number(token.text)
|
|
150
|
+
if (token?.type === '(') {
|
|
151
|
+
const top = this.next()
|
|
152
|
+
if (top?.type !== 'number') throw this.error('A power in parentheses must be a number or a fraction')
|
|
153
|
+
let value = Number(top.text)
|
|
154
|
+
if (this.peek()?.type === '/') {
|
|
155
|
+
this.i++
|
|
156
|
+
const bottom = this.next()
|
|
157
|
+
if (bottom?.type !== 'number' || Number(bottom.text) === 0) throw this.error('A fractional power needs a non-zero denominator')
|
|
158
|
+
value /= Number(bottom.text)
|
|
159
|
+
}
|
|
160
|
+
this.expect(')')
|
|
161
|
+
return value
|
|
162
|
+
}
|
|
163
|
+
throw this.error('A power must follow "^"')
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private power(unit: Unit, n: number): Unit {
|
|
167
|
+
if (unit.isLogarithmic) throw this.error(`${unit} is logarithmic and can't be raised to a power`)
|
|
168
|
+
return unit.pow(n)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private combine(a: Unit, b: Unit, op: 'times' | 'div'): Unit {
|
|
172
|
+
if (a.isLogarithmic || b.isLogarithmic) {
|
|
173
|
+
throw this.error(`${a.isLogarithmic ? a : b} is logarithmic and can't be multiplied or divided`)
|
|
174
|
+
}
|
|
175
|
+
return op === 'times' ? a.times(b) : a.div(b)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
private atEnd(): boolean {
|
|
179
|
+
return this.i >= this.tokens.length
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private peek(): Token | undefined {
|
|
183
|
+
return this.tokens[this.i]
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private next(): Token | undefined {
|
|
187
|
+
return this.tokens[this.i++]
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private expect(type: '(' | ')'): void {
|
|
191
|
+
const token = this.next()
|
|
192
|
+
if (token?.type !== type) throw this.error(`Expected "${type}"`)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private describe(token: Token | undefined): string {
|
|
196
|
+
if (!token) return 'the end'
|
|
197
|
+
if (token.type === 'symbol' || token.type === 'number') return token.text
|
|
198
|
+
return token.type === 'log' ? 'log10' : token.type
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private error(message: string): UnitParseError {
|
|
202
|
+
return new UnitParseError(`${message} (in the unit "${this.text}")`)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const cache = new Map<string, Unit>()
|
|
207
|
+
|
|
208
|
+
/** Reads a unit from text, such as "km/s". Throws a UnitParseError for text it can't read. */
|
|
209
|
+
export function parseUnit(text: string): Unit {
|
|
210
|
+
const cached = cache.get(text)
|
|
211
|
+
if (cached) return cached
|
|
212
|
+
const parsed = new Parser(tokenize(text), text).parse()
|
|
213
|
+
if (cache.size >= 1000) cache.clear()
|
|
214
|
+
cache.set(text, parsed)
|
|
215
|
+
return parsed
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* A unit from its text: `unit("km/s")`. Typed by its kind where the type system knows it; give
|
|
220
|
+
* the kind to name it otherwise, checked when it runs: `unit("au/yr", "speed")`.
|
|
221
|
+
*/
|
|
222
|
+
export function unit<const S extends string>(text: S): Unit<KindOf<S>>
|
|
223
|
+
export function unit<K extends Kind>(text: string, kind: K): Unit<K>
|
|
224
|
+
export function unit(text: string, kind?: string): Unit {
|
|
225
|
+
const parsed = parseUnit(text)
|
|
226
|
+
if (kind !== undefined && parsed.kind !== kind) {
|
|
227
|
+
throw new UnitParseError(`"${text}" is a unit of ${parsed.kind}, not ${kind}`)
|
|
228
|
+
}
|
|
229
|
+
return parsed
|
|
230
|
+
}
|