-
Notifications
You must be signed in to change notification settings - Fork 1
/
dinero.go
83 lines (72 loc) · 2.31 KB
/
dinero.go
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
package dinerogo
import (
"errors"
"golang.org/x/text/language"
)
var DefaultCurrency string = USD
var DefaultPrecision uint8 = 2
var GlobalCurrency string = DefaultCurrency
var GlobalPrecision uint8 = DefaultPrecision
// Dinero: Monetary object representation
type dinero struct {
amount int64 //Amount: The minium unity of the currency (1USD=100cents)
currency string // Currency : Use the ISO4217 format (USD)
precision uint8 // Precision : represent the number of decimal places in the amount
}
// NewDinero : function for create a new dinero object with the Global currency and precision values or for use Default values in the package(USD and 2)
func NewDinero(amount int64) *dinero {
return &dinero{
amount: amount,
currency: GlobalCurrency,
precision: GlobalPrecision,
}
}
// NewDineroWithCurrency: Function for create a new Dinero object using only currency and amount
func NewDineroWithCurrency(amount int64, currency string) (*dinero, error) {
if !IsValidCurrency(currency) {
return nil, errors.New("the currency is not valid in ISO4217")
}
return &dinero{
amount: amount,
currency: currency,
precision: 2,
}, nil
}
// NewDineroWithPrecision : Function for create a new Dinero with custom Precision by default is using 2
func NewDineroWithPrecision(amount int64, precision uint8) *dinero {
return &dinero{
amount: amount,
currency: DefaultCurrency,
precision: precision,
}
}
// NewDineroWithPrecisionAndCurrency : Function for create a new Detailed Dinero object with all parameters
func NewDineroWithPrecisionAndCurrency(amount int64, currency string, precision uint8) (*dinero, error) {
if !IsValidCurrency(currency) {
return nil, errors.New("the currency is not valid in ISO4217")
}
return &dinero{
amount: amount,
currency: currency,
precision: precision,
}, nil
}
// NewDineros: Create a collection for create a dinero array
func NewDineros() []dinero {
return []dinero{}
}
// IsValidCurrency : Check if the currency is valid
func IsValidCurrency(alphabeticCode string) bool {
for _, currency := range ValidCurrency {
code := currency.GetAlphabeticCode()
if code == alphabeticCode {
return true
}
}
return false
}
// IsValidLocale : Check if the locale is valid
func IsValidLocale(locale string) bool {
_, err := language.ParseBase(locale)
return err == nil
}