utils

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 22, 2024 License: MIT Imports: 26 Imported by: 4

README

Utils

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Apr2Apy added in v0.0.5

func Apr2Apy(apr any) float64

Calculate the apy by given apr. Compound times = 365.

Example:

Apr2Apy(0.1) = 0.10515578161622718 // 10%  ==> 10.52%
Apr2Apy(1)   = 1.7145674820220145  // 100% ==> 171.46%

NOTE:

decimal.Decimal method `Pow()` can not use float number as the input parameter,
and therefore using decimal.Decimal is meaningless here.
Example
fmt.Println(Apr2Apy(0.1))
fmt.Println(Apr2Apy(1))
Output:

0.10515578161622718
1.7145674820220145

func Apr2ApyWithCompoundTimes added in v0.0.5

func Apr2ApyWithCompoundTimes[T types.Number](apr any, compoundTimes T) float64

Calculate the apy by given apr.

Example:

Apr2ApyWithCompoundTimes(0.1, 100) = 0.10511569772075302 // 10%  ==> 10.51%
Apr2ApyWithCompoundTimes(1, 100)   = 1.704813829421529   // 100% ==> 170.48%

func Apy2Apr added in v0.0.5

func Apy2Apr(apy any) float64

Calculate the apr by given apy. Compound times = 365.

Example:

Apy2Apr(0.1) = 0.09532262476476205 // 10%  ==> 9.53%
Apy2Apr(1)   = 0.693805752190747   // 100% ==> 69.38%
Example
fmt.Println(Apy2Apr(0.1))
fmt.Println(Apy2Apr(1))
Output:

0.09532262476476205
0.693805752190747

func Apy2AprWithCompoundTimes added in v0.0.5

func Apy2AprWithCompoundTimes[T types.Number](apy any, compoundTimes T) float64

Calculate the apr by given apy.

Example:

Apy2AprWithCompoundTimes(0.1, 100) = 0.09535561438964724 // 10%  ==> 9.54%
Apy2AprWithCompoundTimes(1, 100)   = 0.6955550056718884  // 100% ==> 69.56%

func ArrayAnd added in v0.3.2

func ArrayAnd[T comparable](array0, array1 []T) []T

Return the AND result of two arrays.

func ArrayOr added in v0.3.2

func ArrayOr[T comparable](array0, array1 []T) []T

Return the OR result of two arrays.

func BigSqrt added in v0.2.5

func BigSqrt(num *big.Int, times int) *big.Int

Sqrt for big int.

Examples:

BigSqrt(100, 2) = 10
BigSqrt(1000, 3) = 10

func Celcius2Fahrenheit added in v0.0.9

func Celcius2Fahrenheit[T types.OrderedNumber](degree T) float64

func ChecksumEthereumAddress

func ChecksumEthereumAddress(addr string) string

Return checksummed ethereum address.

Example
fmt.Println(ChecksumEthereumAddress("0x5750bd75ADC81367D1b7510A57D79ACF777950a1")) // checksumed
fmt.Println(ChecksumEthereumAddress("0x5750bd75adc81367d1b7510a57d79acf777950a1")) // all lower case
fmt.Println(ChecksumEthereumAddress("0X5750BD75ADC81367D1B7510A57D79ACF777950A1")) // all upper case
Output:

0x5750bd75ADC81367D1b7510A57D79ACF777950a1
0x5750bd75ADC81367D1b7510A57D79ACF777950a1
0x5750bd75ADC81367D1b7510A57D79ACF777950a1

func ConnectArray

func ConnectArray(connector string, strList ...string) string

Connect the items in an array with "connector".

Example:

ConnectArray([]string{"one", "year", "old"}..., "-") = "one-year-old"

func ContainAllOfStrs added in v0.2.4

func ContainAllOfStrs(str string, subStrs []string) bool

Example:

ContainAnyOfStrs("abracadabra", []string{"bra", "abr"}) = true
ContainAnyOfStrs("abracadabra", []string{"bra", "tnt"}) = false

func ContainAnyOfStrs

func ContainAnyOfStrs(str string, subStrs []string) bool

Example:

ContainAnyOfStrs("abracadabra", []string{"bra", "tnt"}) = true
ContainAnyOfStrs("abracadabra", []string{"abc", "tnt"}) = false

func ContainInArray

func ContainInArray[T comparable](target T, array ...T) bool

If target contains in array.

Example:

ContainInArray(1,[]int{1, 2, 3}) = true
ContainInArray("", []string{"1", "2", "3"}...) = false
ContainInArray("0", []string{"1", "2", "3"}...) = false

func ContainInArrayX added in v0.0.6

func ContainInArrayX(target string, array ...string) bool

If target contains in string array, ignore lower or upper.

Example:

ContainInArrayX("aa", []string{"aa", "bb", "cc"}...) = true
ContainInArrayX("aA", []string{"aa", "bb", "cc"}...) = true

func CreateKey

func CreateKey() (privateKey string, address string)

Create a pair of private key and address.

func CryptoRandBelow

func CryptoRandBelow[T types.Integer](length T) int

Real random/ Crypto random.

Range:

0 ~ length-1

func CryptoRandBetween

func CryptoRandBetween(start int, end int, times int) []int

Choose "times" different numbers between "start" and "end".

Example:

CryptoRandBetween(1, 100, 5) = []int{1, 68, 69, 78, 79, 98, 100}

func CryptoRandFrom added in v0.2.2

func CryptoRandFrom[T any](range_ ...T) T

Choose an element randomly from the given array.

func Fahrenheit2Celcius added in v0.0.9

func Fahrenheit2Celcius[T types.OrderedNumber](degree T) float64

func FindAddressContain added in v0.2.1

func FindAddressContain(times int, targets ...string) []findAddr

Find an address contain the target string.

func FindAddressEnd added in v0.2.1

func FindAddressEnd(times int, targets ...string) []findAddr

Find an address end with the target string.

func FindAddressStart added in v0.2.1

func FindAddressStart(times int, targets ...string) []findAddr

Find an address start with the target string.

func FindBytesBetween

func FindBytesBetween(fullBytes []byte, bytesBefore []byte, bytesAfter []byte) (target [][]byte)

Find all []byte between "bytesBefore" and "bytesAfter".

Used to seperate a long []byte into ideal array.

func FindStringBetween

func FindStringBetween(fullStr string, strBefore string, strAfter string) (target []string)

Find all string between "strBefore" and "strAfter".

Used to seperate a long string into ideal array.

Example:

FindStringBetween("aaaaaa", "a", "a") = []string{"", "", ""}
FindStringBetween("abcabc", "a", "c") = []string{"b", "b"}

func FormatJson

func FormatJson(obj any) string

func FormatJsonByte

func FormatJsonByte(obj any) []byte

func GetHashAsPriv added in v0.0.9

func GetHashAsPriv(input string) (hashStr string, address string)

Get hash and use it as private key, and generate an eth address.

Return:

1st. string: The hash. If "0x" deleted, it is the private key.
2nd. string: The ethereum address generated by the hash.

Example:

GetHashAsPriv("8") =
 "0xe4b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10",
 "0xe0FC04FA2d34a66B779fd5CEe748268032a146c0"
Example
priv, addr := GetHashAsPriv("100")
fmt.Println("priv:", priv)
fmt.Println("addr:", addr)
Output:

priv: 0x8c18210df0d9514f2d2e5d8ca7c100978219ee80d3968ad850ab5ead208287b3
addr: 0xef3CDbFf03CE88F5041C82131b0cF15061b6015E

func GetStringHash

func GetStringHash(input string) (hash string)

Get the hash of a string.

Example:

GetStringHash("TraderJoeSupplyEvent(address,address,uint256,address)") = "0x222da511b15d564e69f7e3832eaefbe7fb9875c94fbeecdc358917f0fd0a4f9f"

func LowerFirst added in v0.0.9

func LowerFirst(str string) string

The first letter to lower case.

Example:

LowerFirst("Lower") = "lower"

func MathRandBelow

func MathRandBelow[T types.Integer](length T) int

Random from timestamp.

Range:

0 ~ length-1

func Max added in v0.0.4

func Max[T types.OrderedNumber](numbers ...T) T

Get the maximum one of the input numbers.

Example:

Max(1, 2, 3) = 3
Max[int]()   = 0
Max([]int{2, 3, 4}...) = 4
Example
fmt.Println(Max[int]())
fmt.Println(Max[float64](1, 2))
fmt.Println(Max(1, 2, 3, 4, 5))
fmt.Println(Max([]int{2, 3, 4}...))
Output:

0
2
5
4

func Mean added in v0.3.3

func Mean[T types.OrderedNumber](numbers ...T) float64

func Medium added in v0.2.3

func Medium[T types.OrderedNumber](numbers ...T) float64

Get the medium number.

Example
list := []int{1, 2, 5, 4, 3}
fmt.Println(Medium(list...))

list = []int{1, 2, 5, 4, 3, 2}
fmt.Println(Medium(list...))
Output:

3
2.5

func Min added in v0.0.4

func Min[T types.OrderedNumber](numbers ...T) T

Get the minimum one of the input numbers.

Example:

Min(1, 2, 3) = 1
Min[int]()   = 0
Min([]int{2, 3, 4}...) = 2
Example
fmt.Println(Min[int]())
fmt.Println(Min[float64](1, 2))
fmt.Println(Min(1, 2, 3, 4, 5))
fmt.Println(Min([]int{2, 3, 4}...))
Output:

0
1
1
2

func Mode added in v0.2.3

func Mode[T types.OrderedNumber](numbers ...T) []T

Get the mode(math).

Example
list := []int{1, 2, 5, 4, 3, 2}
fmt.Println(Mode(list...))
list = []int{1, 2, 5, 4, 3, 2, 3, 4}
fmt.Println(Mode(list...))
Output:

[2]
[2 3 4]

func PadToLength added in v0.4.0

func PadToLength(str string, length int, fillWith ...string) string

Fill the string to a certain length.

Example:

PadToLength("xx", 5, "-") = "xx---"
Example
fmt.Println(PadToLength("xx", 5, "-"))
Output:

xx---

func PathExist added in v0.3.0

func PathExist(path string) bool

Return if the path exists.

func PathIsDir added in v0.3.0

func PathIsDir(path string) bool

Return if the path is dir.

func PrettifyJson

func PrettifyJson(raw string) string

func PrettyJsonPrintln

func PrettyJsonPrintln(obj any)

func Private2Address added in v0.0.9

func Private2Address(key string) string

From private key to address.

Example
fmt.Println(Private2Address("3fe74272f214ddb0d182a9ae68e3ee844d6f61d04f6e7827aad972e071a31f81"))
Output:

0x5750bd75ADC81367D1b7510A57D79ACF777950a1

func ReadCsv

func ReadCsv(filePath string) (contents [][]string, err error)

Read the csv file from the given path. The first line of the result is the title.

func ReadJson added in v0.2.4

func ReadJson(path string, v any) error

Read json file into []byte and unmarshal into v.

func ReadJsonBytes added in v0.2.4

func ReadJsonBytes(path string) ([]byte, error)

Read json file into []byte.

func ReadJsonSlice

func ReadJsonSlice(path string) ([]string, error)

Read json file into []byte and unmarshal into []string.

func ReadJsonString added in v0.2.4

func ReadJsonString(path string) (string, error)

Read json file into []byte and convert into string.

func RemoveFromArray

func RemoveFromArray[T comparable](toRemove T, array ...T) []T

Remove sth from an array and return the new one.

Example:

RemoveFromArray("aa", []string{"aa", "bb"}...) = []string{"bb"}
RemoveFromArray(1, []uint64{1}...) = []uint64{}

func RemoveFromString

func RemoveFromString(str string, subStr string) string

Remove the first subStr in str.

func RemoveRepetitionInArray

func RemoveRepetitionInArray[T comparable](array ...T) []T

Remove repetiton in an array and return the new one.

Example:

RemoveRepetitionInArray([]string{"aa", "bb", "bb", "BB"}...) = []string{"aa", "bb", "BB"}
RemoveRepetitionInArray([]int{1, 2, 3, 3}...) = []int{1, 2, 3}

func Restart

func Restart(funcToRecover func())

Recover from panic and restart.

func RestartAndSleep

func RestartAndSleep(funcToRecover func(), sleepTime time.Duration)

Recover from panic and restart after waiting for a while.

func RunFuncName added in v0.0.8

func RunFuncName() (name string)

Get the function name running now.

Example
fmt.Println(RunFuncName())
Output:

github.com/0xVanfer/utils.ExampleRunFuncName

func SendTelegramSimple added in v0.0.7

func SendTelegramSimple(botToken string, chatId int64, text string) error

Send simple telegram message.

Param:

botToken: Telegram bot token, you can search for
		  `BotFather` in telegram and generate your own bot.
chatId:   If you are sending a message to a user, chatId is his id, a possitive integer,
	      like 12345678, which the user can get by starting `userinfobot`.
          If you are sending a message to a group, chatId is a negative integer.

NOTE:

Can only send simple text. Not support `\` like `\n`.

func SeperateIntoArray

func SeperateIntoArray(str string, seperateBy string) (res []string)

Seperate a string into an array, the seperater will be deleted.

Example:

SeperateIntoArray("one-year-old", "-") = []string{"one", "year", "old"}

func SimpleMarshal

func SimpleMarshal(obj any) []byte

func SimpleStringify

func SimpleStringify(obj any) string

func SolveSimpleEquations added in v0.3.1

func SolveSimpleEquations(params ...float64) []float64

Solve the equation(within cubic).

func SortSimple added in v0.2.3

func SortSimple[T types.Ordered](ascending bool, input ...T) []T

Simple sort. Do not need to define Len(), Less(), Swap().

Should not be used to sort too much amount of values. If the length is over 12, sort.Sort() suggested.

`ascending`: True: The result will be ascending. False: The result will be descending.

Example:

SortSimple(true, []int{1, 2, 5, 6, 3, 12}...) = []int{1, 2, 3, 5, 6, 12}

func SortSimpleMap added in v0.2.3

func SortSimpleMap[S comparable, T types.Ordered](ascending bool, input map[S]T) ([]S, []T)

Simple sort by map value. Do not need to define Len(), Less(), Swap().

Should not be used to sort too much amount of values. If the length is over 12, sort.Sort() suggested.

Returns the ordered keys and ordered values.

Example:

mapp := map[string]int{
	"a": 1,
	"b": 3,
	"c": 4,
	"d": 2,
}
x, y := SortSimpleMap(true, mapp)
x = []string{"a", "d", "b", "c"}
y = []int{1, 2, 3, 4}

func StrCamel2Underline added in v0.0.9

func StrCamel2Underline(str string) string

Return underline case of str.

Example:

StrUnderline2Camel("aBC") = "a_b_c"
StrUnderline2Camel("ABC") = "a_b_c"

NOTE:

Using both `StrUnderline2Camel()` and `StrCamel2Underline()`
(regardless of order) will probably not get the original string!
Example
fmt.Println(StrCamel2Underline("aaBBC"))
fmt.Println(StrCamel2Underline("A"))
fmt.Println(StrCamel2Underline("bASccccSS"))
Output:

aa_b_b_c
a
b_a_scccc_s_s

func StrUnderline2Camel added in v0.0.9

func StrUnderline2Camel(str string) string

Return camel case of str. The first letter is lower case.

Example:

StrUnderline2Camel("a_b_c") = "aBC"

NOTE:

Using both `StrUnderline2Camel()` and `StrCamel2Underline()`
(regardless of order) will probably not get the original string!
Example
fmt.Println(StrUnderline2Camel(""))
fmt.Println(StrUnderline2Camel("a"))
fmt.Println(StrUnderline2Camel("a_b"))
fmt.Println(StrUnderline2Camel("a_b_ccc_ddd"))
// Output
//
// a
// aB
// aBCccDdd
Output:

func StrUnderline2CamelUpperFirst added in v0.0.9

func StrUnderline2CamelUpperFirst(str string) string

Return camel case of str. The first letter is upper case.

Example:

StrUnderline2Camel("a_b_c") = "ABC"

NOTE:

Using both `StrUnderline2Camel()` and `StrCamel2Underline()`
(regardless of order) will probably not get the original string!

func StrUnderline2Seperate added in v0.0.9

func StrUnderline2Seperate(str string) string

Return seperated words of str.

Example:

StrUnderline2Seperate("a_b_c") = "a b c"
Example
fmt.Println(StrUnderline2Seperate(""))
fmt.Println(StrUnderline2Seperate("a"))
fmt.Println(StrUnderline2Seperate("a_b"))
fmt.Println(StrUnderline2Seperate("a_b_ccc_ddd"))
Output:


a
a b
a b ccc ddd

func StrUnderline2SeperateTitle added in v0.0.9

func StrUnderline2SeperateTitle(str string) string

Return title case seperated words of str.

Example:

StrUnderline2SeperateTitle("a_b_c") = "A B C"
Example
fmt.Println(StrUnderline2SeperateTitle(""))
fmt.Println(StrUnderline2SeperateTitle("a"))
fmt.Println(StrUnderline2SeperateTitle("a_b"))
fmt.Println(StrUnderline2SeperateTitle("a_b_ccc_ddd"))
// Output
//
// A
// A B
// A B Ccc Ddd
Output:

func StringToTrueLocations

func StringToTrueLocations(str string) []int64

Consider a map: map[loc]=bool.

Convert the coded string into locations.

Example:

StringToTrueLocations("1432351") =
[]int64{0, 1, 2, 3, 4, 8, 9, 11, 12, 14, 15, 16, 18, 20}
Example
fmt.Println(StringToTrueLocations("1432351"))
Output:

[0 1 2 3 4 8 9 11 12 14 15 16 18 20]

func Stringify

func Stringify(obj any) string

func Sum added in v0.3.2

func Sum[T types.OrderedNumber](numbers ...T) T

Get the sum.

func TrueLocationsToString

func TrueLocationsToString(trueLocs ...int64) string

Consider a map: map[loc]=bool.

Use a bigInt to locate all true locations and convert into string.

Example:

TrueLocationsToString([]int64{1, 2, 333}...) =
"17498005798264095394980017816940970922825355447145699491406164851279623993595007385788105416184430598"
Example
fmt.Println(TrueLocationsToString([]int64{1, 2, 33}...))
Output:

8589934598

func UpperFirst added in v0.0.9

func UpperFirst(str string) string

The first letter to upper case.

Example:

UpperFirst("upper") = "Upper"

func Variance added in v0.3.3

func Variance[T types.OrderedNumber](numbers ...T) float64

func WriteNewCsv

func WriteNewCsv(filePath string, title []string, text [][]string) error

Write a new csv file. If file exist, will cover the old file.

func WriteToCsv

func WriteToCsv(filePath string, title []string, text ...[]string) error

Write to csv line by line.

func WriteToCsvResume added in v0.0.6

func WriteToCsvResume(filePath string, title []string, text []string, noRepeatTitle string) error

Write to csv line by line.

Will not write the text if the value of "noRepeatTitle" already exists.

For example, the csv already exists, and there is a column named "name" with values: Alice, Bob. `noRepeatTitle` is "name". If the function is called with "name" value "Alice", this line will be skipped.

Types

type CurveStableCoinModel added in v0.2.7

type CurveStableCoinModel struct {
	// Input info.
	A   int64   // Amplification. A != 0.
	N   int64   // Token number. N >= 2.
	Fee float64 // Curve Fee. Usually 0.0004.

	// Input info.
	// Token amount info. Must be multiplied by 1e18.
	Balances []*big.Int // Pool balance of tokens. len(Balances) == N.
	Dx       *big.Int   // Swap amount of token x.
	X_Num    int64      // The serial number of the token to be swaped. Related to `Balances`.
	Y_Num    int64      // The serial number of the token to be swaped to. Related to `Balances`.

	// Output info.
	D           *big.Int // Variable D of the pool.
	ExpectedFee *big.Int // Expected fee to be charged.
	ExpectedDy  *big.Int // Expected give out amount of token y.
	// contains filtered or unexported fields
}

Curve stable coin model.

Example:

info := &CurveStableCoinModel{
	A:     50,
	N:     2,
	X_Num: 0,
	Y_Num: 1,
	Fee:   0.0004,
	Balances: []*big.Int{
		big.NewInt(1).Mul(big.NewInt(409880), big.NewInt(1e18)),
		big.NewInt(1).Mul(big.NewInt(244647), big.NewInt(1e18)),
	},
	Dx: big.NewInt(1).Mul(big.NewInt(1), big.NewInt(1e18)),
}
info.CalcDy()
utils.PrettyJsonPrintln(info)

func (*CurveStableCoinModel) CalcDy added in v0.2.7

func (details *CurveStableCoinModel) CalcDy() (err error)

Calculate everything.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL