This repository has been archived by the owner on Sep 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
currency.coffee
74 lines (53 loc) · 2.39 KB
/
currency.coffee
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
import currencies from './data/currencies'
currencySeparator = '.'
digitsOnlyRe = new RegExp('[^\\d.-]', 'g')
currencySigns = currencies.data
# Does the currency support decimal notation
export isZeroDecimal = (code)->
code = code.toLowerCase() if code
if code == 'bif' || code == 'clp' || code == 'djf' || code == 'gnf' || code == 'jpy' || code == 'kmf' || code == 'krw' || code == 'mga' || code == 'pyg' || code == 'rwf' || code == 'vnd' || code == 'vuv' || code == 'xaf' || code == 'xof' || code == 'xpf'
return true
return false
# Is the currency code a crypto currency?
export isCrypto = (code)->
return code == 'eth' || code == 'btc' || code =='xbt'
# Convert humanized currency format to data format back to currency format
export renderUpdatedUICurrency = (code, uiCurrency) ->
code = code.toLowerCase() if code
return renderUICurrencyFromJSON code, renderJSONCurrencyFromUI(code, uiCurrency)
# Convert data format to humanized format
export renderUICurrencyFromJSON = (code, jsonCurrency) ->
code = code.toLowerCase() if code
if isNaN jsonCurrency
jsonCurrency = 0
currentCurrencySign = currencySigns[code] ? ''
# ethereum
if code == 'eth' || code == 'btc' || code =='xbt'
jsonCurrency = jsonCurrency / 1e9
return currentCurrencySign + jsonCurrency
jsonCurrency = '' + jsonCurrency
# jsonCurrency is not cents
if isZeroDecimal code
return currentCurrencySign + jsonCurrency
# jsonCurrency is cents
while jsonCurrency.length < 3
jsonCurrency = '0' + jsonCurrency
return currentCurrencySign + jsonCurrency.substr(0, jsonCurrency.length - 2) + '.' + jsonCurrency.substr(-2)
# Convert humanized format to data format
export renderJSONCurrencyFromUI = (code, uiCurrency) ->
code = code.toLowerCase() if code
currentCurrencySign = currencySigns[code]
# ethereum
if code == 'eth' || code == 'btc' || code =='xbt'
return parseFloat(('' + uiCurrency).replace(digitsOnlyRe, '')) * 1e9
if isZeroDecimal code
return parseInt(('' + uiCurrency).replace(digitsOnlyRe, '').replace(currencySeparator, ''), 10)
# uiCurrency is a whole unit of currency
parts = uiCurrency.split currencySeparator
if parts.length > 1
parts[1] = parts[1].substr(0, 2)
while parts[1].length < 2
parts[1] += '0'
else
parts[1] = '00'
return parseInt(parseFloat(parts[0].replace(digitsOnlyRe, '')) * 100 + parseFloat(parts[1].replace(digitsOnlyRe, '')), 10)