-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
apply.ts
21 lines (20 loc) · 723 Bytes
/
apply.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import Big from 'big.js'
import {CurrencyCode, CurrencyRates} from './currencies'
import {Nothing, Numbr, Result} from './results'
export function apply(
op: (x: Big, y: Big) => Big,
x: Numbr,
y: Numbr,
rates: CurrencyRates
): Numbr {
if (x.currency == undefined || y.currency == undefined) {
return new Numbr(op(x.value, y.value), y.currency || x.currency)
}
if (x.currency == y.currency) {
return new Numbr(op(x.value, y.value), y.currency)
}
if (rates[x.currency] == undefined || rates[y.currency] == undefined) {
throw new Error(`No currency rates for ${x.currency}/${y.currency}.`)
}
return new Numbr(op(x.value.mul(rates[x.currency]).div(rates[y.currency]), y.value), y.currency)
}