-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
401 lines (328 loc) · 10.3 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import { isFunction, isNaN, isObject, isPlainObject, isString } from 'lodash'
import { Currency } from './lib/currency'
import { Currencies } from './lib/currencies'
export type Rounder = 'round' | 'floor' | 'ceil' | Function;
export interface Amount {
amount: number;
currency: string | Currency
}
let isInt = function (n) {
return Number(n) === n && n % 1 === 0
}
let decimalPlaces = function (num) {
let match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/)
if (!match)
return 0
return Math.max(0,
(match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0))
}
let assertSameCurrency = function (left, right) {
if (left.currency !== right.currency)
throw new Error('Different currencies')
}
let assertType = function (other) {
if (!(other instanceof Money))
throw new TypeError('Instance of Money required')
}
let assertOperand = function (operand) {
if (isNaN(parseFloat(operand)) && !isFinite(operand))
throw new TypeError('Operand must be a number')
}
let getCurrencyObject = function (currency: string): Currency {
let currencyObj = Currencies[currency]
if (currencyObj) {
return currencyObj
}
else {
for (let key in Currencies) {
if (key.toUpperCase() === currency.toUpperCase())
return Currencies[key]
}
}
}
function isAmountObject(amount: number | Amount): amount is Amount {
return isObject(amount);
}
class Money {
amount: number
currency: string
/**
* Creates a new Money instance.
* The created Money instances is a value object thus it is immutable.
*
* @param {Number} amount
* @param {Object/String} currency
* @returns {Money}
* @constructor
*/
constructor(amount: number, currency: Currency | string) {
if (isString(currency))
currency = getCurrencyObject(currency)
if (!isPlainObject(currency))
throw new TypeError('Invalid currency')
if (!isInt(amount))
throw new TypeError('Amount must be an integer')
this.amount = amount
this.currency = currency.code
Object.freeze(this)
}
static fromInteger(amount: Amount): Money;
static fromInteger(amount: number, currency: Currency | string): Money
static fromInteger(amount: number | Amount, currency?: Currency | string): Money {
if (isAmountObject(amount)) {
if (amount.amount === undefined || amount.currency === undefined)
throw new TypeError('Missing required parameters amount,currency')
currency = amount.currency
amount = amount.amount
}
if (!isInt(amount))
throw new TypeError('Amount must be an integer value')
return new Money(amount, currency)
}
static fromDecimal(amount: Amount, rounder?: Rounder): Money;
static fromDecimal(amount: number, currency: string | Currency, rounder?: Rounder): Money;
static fromDecimal(amount: number | Amount, currency: string | Currency | any, rounder?: Rounder): Money {
if (isAmountObject(amount)) {
if (amount.amount === undefined || amount.currency === undefined)
throw new TypeError('Missing required parameters amount,currency')
rounder = currency
currency = amount.currency
amount = amount.amount
}
if (isString(currency))
currency = getCurrencyObject(currency)
if (!isPlainObject(currency))
throw new TypeError('Invalid currency')
if (rounder === undefined) {
let decimals = decimalPlaces(amount)
if (decimals > currency.decimal_digits)
throw new Error(`The currency ${currency.code} supports only` +
` ${currency.decimal_digits} decimal digits`)
rounder = Math.round
} else {
if (['round', 'floor', 'ceil'].indexOf(rounder as string) === -1 && typeof rounder !== 'function')
throw new TypeError('Invalid parameter rounder')
if (isString(rounder))
rounder = Math[rounder]
}
let precisionMultiplier = Math.pow(10, currency.decimal_digits)
let resultAmount = amount * precisionMultiplier
resultAmount = (rounder as Function)(resultAmount)
return new Money(resultAmount, currency)
}
/**
* Returns true if the two instances of Money are equal, false otherwise.
*
* @param {Money} other
* @returns {Boolean}
*/
equals(other: Money): boolean {
let self = this
assertType(other)
return self.amount === other.amount &&
self.currency === other.currency
}
/**
* Adds the two objects together creating a new Money instance that holds the result of the operation.
*
* @param {Money} other
* @returns {Money}
*/
add(other: Money): Money {
let self = this
assertType(other)
assertSameCurrency(self, other)
return new Money(self.amount + other.amount, self.currency)
}
/**
* Subtracts the two objects creating a new Money instance that holds the result of the operation.
*
* @param {Money} other
* @returns {Money}
*/
subtract(other: Money): Money {
let self = this
assertType(other)
assertSameCurrency(self, other)
return new Money(self.amount - other.amount, self.currency)
}
/**
* Multiplies the object by the multiplier returning a new Money instance that holds the result of the operation.
*
* @param {Number} multiplier
* @param {Function} [fn=Math.round]
* @returns {Money}
*/
multiply(multiplier: number, fn?: Function): Money {
if (!isFunction(fn))
fn = Math.round
assertOperand(multiplier)
let amount = fn(this.amount * multiplier)
return new Money(amount, this.currency)
}
/**
* Divides the object by the multiplier returning a new Money instance that holds the result of the operation.
*
* @param {Number} divisor
* @param {Function} [fn=Math.round]
* @returns {Money}
*/
divide(divisor: number, fn?: Function): Money {
if (!isFunction(fn))
fn = Math.round
assertOperand(divisor)
let amount = fn(this.amount / divisor)
return new Money(amount, this.currency)
}
/**
* Allocates fund bases on the ratios provided returing an array of objects as a product of the allocation.
*
* @param {Array} other
* @returns {Array.Money}
*/
allocate(ratios: number[]): Money[] {
let self = this
let remainder = self.amount
let results = []
let total = 0
ratios.forEach(function (ratio) {
total += ratio
})
ratios.forEach(function (ratio) {
let share = Math.floor(self.amount * ratio / total)
results.push(new Money(share, self.currency))
remainder -= share
})
for (let i = 0; remainder > 0; i++) {
results[i] = new Money(results[i].amount + 1, results[i].currency)
remainder--
}
return results
}
/**
* Compares two instances of Money.
*
* @param {Money} other
* @returns {Number}
*/
compare(other: Money): number {
let self = this
assertType(other)
assertSameCurrency(self, other)
if (self.amount === other.amount)
return 0
return self.amount > other.amount ? 1 : -1
}
/**
* Checks whether the value represented by this object is greater than the other.
*
* @param {Money} other
* @returns {boolean}
*/
greaterThan(other: Money): boolean {
return 1 === this.compare(other)
}
/**
* Checks whether the value represented by this object is greater or equal to the other.
*
* @param {Money} other
* @returns {boolean}
*/
greaterThanOrEqual(other: Money): boolean {
return 0 <= this.compare(other)
}
/**
* Checks whether the value represented by this object is less than the other.
*
* @param {Money} other
* @returns {boolean}
*/
lessThan(other: Money): boolean {
return -1 === this.compare(other)
}
/**
* Checks whether the value represented by this object is less than or equal to the other.
*
* @param {Money} other
* @returns {boolean}
*/
lessThanOrEqual(other: Money): boolean {
return 0 >= this.compare(other)
}
/**
* Returns true if the amount is zero.
*
* @returns {boolean}
*/
isZero(): boolean {
return this.amount === 0
}
/**
* Returns true if the amount is positive.
*
* @returns {boolean}
*/
isPositive(): boolean {
return this.amount > 0
}
/**
* Returns true if the amount is negative.
*
* @returns {boolean}
*/
isNegative(): boolean {
return this.amount < 0
}
/**
* Returns the decimal value as a float.
*
* @returns {number}
*/
toDecimal(): number {
return Number(this.toString())
}
/**
* Returns the decimal value as a string.
*
* @returns {string}
*/
toString(): string {
let currency = getCurrencyObject(this.currency)
return (this.amount / Math.pow(10, currency.decimal_digits)).toFixed(currency.decimal_digits)
}
/**
* Returns a serialised version of the instance.
*
* @returns {{amount: number, currency: string}}
*/
toJSON(): {amount: number, currency: string} {
return {
amount: this.amount,
currency: this.currency
}
}
/**
* Returns the amount represented by this object.
*
* @returns {number}
*/
getAmount(): number {
return this.amount
}
/**
* Returns the currency represented by this object.
*
* @returns {string}
*/
getCurrency(): string {
return this.currency
}
/**
* Returns the full currency object
*/
getCurrencyInfo(): Currency {
return getCurrencyObject(this.currency)
}
}
Object.assign(Money, Currencies)
export { Money, Currencies, Currency }