hg

package module
v1.0.34 Latest Latest
Warning

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

Go to latest
Published: May 22, 2023 License: MIT Imports: 39 Imported by: 2

README

🤪 Humango: Go Crazy, Go Human, Go Nuts!

Go Reference Go Report Card

Introducing Humango, the wackiest Go package on the planet, created to make your coding experience an absolute riot! With Humango, you can forget about dull and monotonous code; we're all about turning the mundane into the insanely hilarious. It's not just a bicycle; it's almost a motorcycle 🤣!

🎉 What's in the box?

  1. 📖 Readable syntax: Boring code is so yesterday! Humango turns your code into a party by blending seamlessly with Go and making it super clean and laughably maintainable.
  2. 🔀 Encoding and decoding: Juggling data formats? No problemo! Humango's got your back with Base64, URL, Gzip, and Rot13 support. Encode and decode like a pro!
  3. 🔒 Hashing extravaganza: Safety first, right? Hash your data with MD5, SHA1, SHA256, or SHA512, and enjoy peace of mind while Humango watches over your bytes.
  4. 📁 File and directory shenanigans: Create, read, write, and dance through files and directories with Humango's fun-tastic functions. Trust us, managing files has never been this entertaining.
  5. 🌈 Data type compatibility: Strings, integers, floats, bytes, slices, maps, you name it! Humango is the life of the party, mingling with all your favorite data types.
  6. 🔧 Customize and extend: Need something extra? Humango is your best buddy, ready to be extended or modified to suit any project.
  7. 📚 Docs & examples: We're not just about fun and games, we've got detailed documentation and examples that'll have you smiling from ear to ear as you learn the Humango way.

Take your Go projects to a whole new level of excitement with Humango! It's time to stop coding like it's a chore and start coding like it's a celebration! 🥳

Examples

Generate a securely random string.

stdlib hg
func main() {
	const charset = "abcdefghijklmnopqrstuvwxyz" +
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

	length := 10

	b := make([]byte, length)
	if _, err := rand.Read(b); err != nil {
		return
	}

	for i, v := range b {
		b[i] = charset[v%byte(len(charset))]
	}

	result := string(b)
	fmt.Println(result)
}
func main() {
	result := hg.NewHString().Random(10)
	fmt.Println(result)
}

GetOrDefault returns the value for a key. If the key does not exist, returns the default value instead. This function is useful when you want to provide a fallback value for keys that may not be present in the map.

stdlib hg
func main() {
	md := map[int][]int{}

	for i := 0; i < 5; i++ {
		value, ok := md[i]
		if !ok {
			value = []int{}
		}

		md[i] = append(value, i)
	}

	fmt.Println(md)
}
func main() {
	md := hg.NewHMap[int, hg.HSlice[int]]()

	for i := range iter.N(5) {
		md.Set(i, md.GetOrDefault(i, hg.NewHSlice[int]()).Append(i))
	}
}

CopyDir copies the contents of the current directory to the destination directory.

stdlib hg
func copyDir(src, dest string) error {
	return filepath.Walk(src, func(path string,
		info fs.FileInfo, err error,
	) error {
		if err != nil {
			return err
		}

		relPath, err := filepath.Rel(src, path)
		if err != nil {
			return err
		}

		destPath := filepath.Join(dest, relPath)

		if info.IsDir() {
			return os.MkdirAll(destPath, info.Mode())
		}

		return copyFile(path, destPath, info.Mode())
	})
}

func copyFile(src, dest string, mode fs.FileMode) error {
	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	destFile, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, mode)
	if err != nil {
		return err
	}
	defer destFile.Close()

	_, err = io.Copy(destFile, srcFile)

	return err
}

func main() {
	src := "path/to/source/directory"
	dest := "path/to/destination/directory"

	err := copyDir(src, dest)
	if err != nil {
		fmt.Println("Error copying directory:", err)
	} else {
		fmt.Println("Directory copied successfully")
	}
}
func main() {
	d := hg.NewHDir(".").CopyDir("copy")

	if d.Error() != nil {
		fmt.Println(d.Error())
	}
}

RandomSample returns a new slice containing a random sample of elements from the original slice.

stdlib hg
func RandomSample(slice []int, amount int) []int {
	if amount > len(slice) {
		amount = len(slice)
	}

	samples := make([]int, amount)

	for i := 0; i < amount; i++ {
		index, _ := rand.Int(rand.Reader, big.NewInt(int64(len(slice))))
		samples[i] = slice[index.Int64()]
		slice = append(slice[:index.Int64()], slice[index.Int64()+1:]...)
	}

	return samples
}

func main() {
	slice := []int{1, 2, 3, 4, 5, 6}
	samples := RandomSample(slice, 3)
	fmt.Println(samples)
}
func main() {
	slice := hg.HSliceOf(1, 2, 3, 4, 5, 6)
	samples := slice.RandomSample(3)
	fmt.Println(samples)
}

Insert inserts values at the specified index in the slice and returns the resulting slice.

stdlib hg
func Insert(slice []int, index int, values ...int) []int {
	total := len(slice) + len(values)
	if total <= cap(slice) {
		slice = slice[:total]
		copy(slice[index+len(values):], slice[index:])
		copy(slice[index:], values)

		return slice
	}

	newSlice := make([]int, total)
	copy(newSlice, slice[:index])
	copy(newSlice[index:], values)
	copy(newSlice[index+len(values):], slice[index:])

	return newSlice
}

func main() {
	slice := []int{1, 2, 3, 4, 5}
	slice = Insert(slice, 2, 6, 7, 8)
	fmt.Println(slice) // Output: [1 2 6 7 8 3 4 5]
}
func main() {
	slice := hg.HSliceOf(1, 2, 3, 4, 5)
	slice = slice.Insert(2, 6, 7, 8)
	fmt.Println(slice) // Output: [1 2 6 7 8 3 4 5]
}

Permutations returns all possible permutations of the elements in the slice.

stdlib hg
func Permutations(slice []int) [][]int {
	if len(slice) <= 1 {
		return [][]int{slice}
	}

	perms := make([][]int, 0)

	for i, elem := range slice {
		rest := make([]int, len(slice)-1)

		copy(rest[:i], slice[:i])
		copy(rest[i:], slice[i+1:])

		subPerms := Permutations(rest)

		for j := range subPerms {
			subPerms[j] = append([]int{elem}, subPerms[j]...)
		}

		perms = append(perms, subPerms...)
	}

	return perms
}

func main() {
	slice := []int{1, 2, 3}
	fmt.Println(Permutations(slice))
	// Output: [[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 2 1] [3 1 2]]
}
func main() {
	slice := hg.HSliceOf(1, 2, 3)
	fmt.Println(slice.Permutations())
	// Output: [[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 2 1] [3 1 2]]
}

Documentation

Index

Constants

View Source
const (
	ASCII_LETTERS   = ASCII_LOWERCASE + ASCII_UPPERCASE
	ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
	ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	DIGITS          = "0123456789"
	HEXDIGITS       = "0123456789abcdefABCDEF"
	OCTDIGITS       = "01234567"
	PUNCTUATION     = `!"#$%&'()*+,-./:;<=>?@[\]^{|}~` + "`"

	FileDefault os.FileMode = 0o644
	DirDefault  os.FileMode = 0o755
	FullAccess  os.FileMode = 0o777
)

Variables

This section is empty.

Functions

This section is empty.

Types

type HBytes

type HBytes []byte

func NewHBytes

func NewHBytes(bs ...[]byte) HBytes

NewHBytes creates a new HBytes value.

func (HBytes) Add

func (hbs HBytes) Add(bs HBytes) HBytes

Add appends the given HBytes to the current HBytes.

func (HBytes) AddPrefix

func (hbs HBytes) AddPrefix(bs HBytes) HBytes

AddPrefix prepends the given HBytes to the current HBytes.

func (HBytes) Bytes

func (hbs HBytes) Bytes() []byte

Bytes returns the HBytes as a byte slice.

func (HBytes) Clone

func (hbs HBytes) Clone() HBytes

Clone creates a new HBytes instance with the same content as the current HBytes.

func (HBytes) Compare

func (hbs HBytes) Compare(bs HBytes) HInt

Compare compares the HBytes with another HBytes and returns an HInt.

func (HBytes) Contains

func (hbs HBytes) Contains(bs HBytes) bool

Contains checks if the HBytes contains the specified HBytes.

func (HBytes) ContainsAll added in v1.0.7

func (hbs HBytes) ContainsAll(bss ...HBytes) bool

ContainsAll checks if the HBytes contains all of the specified HBytes.

func (HBytes) ContainsAny

func (hbs HBytes) ContainsAny(bss ...HBytes) bool

ContainsAny checks if the HBytes contains any of the specified HBytes.

func (HBytes) ContainsAnyChars added in v1.0.7

func (hbs HBytes) ContainsAnyChars(chars HString) bool

ContainsAnyChart checks if the given HBytes contains any characters from the input HString.

func (HBytes) ContainsRegexp added in v1.0.21

func (hbs HBytes) ContainsRegexp(pattern *regexp.Regexp) bool

ContainsRegexp checks if the HBytes contains a match for the specified regular expression pattern.

func (HBytes) ContainsRune

func (hbs HBytes) ContainsRune(r rune) bool

ContainsRune checks if the HBytes contains the specified rune.

func (HBytes) Count

func (hbs HBytes) Count(bs HBytes) int

Count counts the number of occurrences of the specified HBytes in the HBytes.

func (HBytes) Empty

func (hbs HBytes) Empty() bool

Empty checks if the HBytes is empty.

func (HBytes) Eq

func (hbs HBytes) Eq(bs HBytes) bool

Eq checks if the HBytes is equal to another HBytes.

func (HBytes) EqFold added in v1.0.19

func (hbs HBytes) EqFold(bs HBytes) bool

EqFold compares two HBytes slices case-insensitively.

func (HBytes) Gt

func (hbs HBytes) Gt(bs HBytes) bool

Gt checks if the HBytes is greater than another HBytes.

func (HBytes) HString

func (hbs HBytes) HString() HString

HString returns the HBytes as an HString.

func (HBytes) Hash

func (hbs HBytes) Hash() bhash

Hash returns a bhash struct wrapping the given HBytes.

func (HBytes) Index added in v1.0.19

func (hbs HBytes) Index(bs HBytes) int

Index returns the index of the first instance of bs in hbs, or -1 if bs is not present in hbs.

func (HBytes) IndexByte added in v1.0.19

func (hbs HBytes) IndexByte(b byte) int

IndexByte returns the index of the first instance of the byte b in hbs, or -1 if b is not present in hbs.

func (HBytes) IndexRune added in v1.0.19

func (hbs HBytes) IndexRune(r rune) int

IndexRune returns the index of the first instance of the rune r in hbs, or -1 if r is not present in hbs.

func (HBytes) Len

func (hbs HBytes) Len() int

Len returns the length of the HBytes.

func (HBytes) LenRunes

func (hbs HBytes) LenRunes() int

LenRunes returns the number of runes in the HBytes.

func (HBytes) Lt

func (hbs HBytes) Lt(bs HBytes) bool

Lt checks if the HBytes is less than another HBytes.

func (HBytes) Map

func (hbs HBytes) Map(fn func(rune) rune) HBytes

Map applies a function to each rune in the HBytes and returns the modified HBytes.

func (HBytes) Ne

func (hbs HBytes) Ne(bs HBytes) bool

Ne checks if the HBytes is not equal to another HBytes.

func (HBytes) NormalizeNFC

func (hbs HBytes) NormalizeNFC() HBytes

NormalizeNFC returns a new HBytes with its Unicode characters normalized using the NFC form.

func (HBytes) NotEmpty

func (hbs HBytes) NotEmpty() bool

NotEmpty checks if the HBytes is not empty.

func (HBytes) Reader

func (hbs HBytes) Reader() *bytes.Reader

Reader returns a *bytes.Reader initialized with the content of HBytes.

func (HBytes) Repeat

func (hbs HBytes) Repeat(count int) HBytes

Repeat returns a new HBytes consisting of the current HBytes repeated 'count' times.

func (HBytes) Replace

func (hbs HBytes) Replace(oldB, newB HBytes, n int) HBytes

Replace replaces the first 'n' occurrences of 'oldB' with 'newB' in the HBytes.

func (HBytes) ReplaceAll

func (hbs HBytes) ReplaceAll(oldB, newB HBytes) HBytes

ReplaceAll replaces all occurrences of 'oldB' with 'newB' in the HBytes.

func (HBytes) Reverse

func (hbs HBytes) Reverse() HBytes

Reverse returns a new HBytes with the order of its runes reversed.

func (HBytes) Runes

func (hbs HBytes) Runes() []rune

Runes returns the HBytes as a slice of runes.

func (HBytes) Split

func (hbs HBytes) Split(sep ...HBytes) HSlice[HBytes]

Split splits the HBytes at each occurrence of the specified HBytes separator.

func (HBytes) String

func (hbs HBytes) String() string

String returns the HBytes as a string.

func (HBytes) ToLower

func (hbs HBytes) ToLower() HBytes

ToLower converts the HBytes to lowercase.

func (HBytes) ToTitle

func (hbs HBytes) ToTitle() HBytes

ToTitle converts the HBytes to title case.

func (HBytes) ToUpper

func (hbs HBytes) ToUpper() HBytes

ToUpper converts the HBytes to uppercase.

func (HBytes) Trim

func (hbs HBytes) Trim(cutset HString) HBytes

Trim trims the specified characters from the beginning and end of the HBytes.

func (HBytes) TrimLeft

func (hbs HBytes) TrimLeft(cutset HString) HBytes

TrimLeft trims the specified characters from the beginning of the HBytes.

func (HBytes) TrimPrefix

func (hbs HBytes) TrimPrefix(cutset HBytes) HBytes

TrimPrefix trims the specified HBytes prefix from the HBytes.

func (HBytes) TrimRight

func (hbs HBytes) TrimRight(cutset HString) HBytes

TrimRight trims the specified characters from the end of the HBytes.

func (HBytes) TrimSpace

func (hbs HBytes) TrimSpace() HBytes

TrimSpace trims white space characters from the beginning and end of the HBytes.

func (HBytes) TrimSuffix

func (hbs HBytes) TrimSuffix(cutset HBytes) HBytes

TrimSuffix trims the specified HBytes suffix from the HBytes.

type HDir

type HDir struct {
	// contains filtered or unexported fields
}

func NewHDir

func NewHDir(path HString) *HDir

NewHDir returns a new HDir instance with the given path.

func (*HDir) CopyDir

func (hd *HDir) CopyDir(dest HString) *HDir

CopyDir copies the contents of the current directory to the destination directory.

Parameters:

- dest (HString): The destination directory where the contents of the current directory should be copied.

Returns:

- *HDir: A pointer to a new HDir instance representing the destination directory.

Example usage:

sourceDir := hg.NewHDir("path/to/source")
destinationDir := sourceDir.CopyDir("path/to/destination")

func (HDir) Error

func (hd HDir) Error() error

Error returns the latest error that occurred during an operation.

func (HDir) Exist

func (hd HDir) Exist() bool

Exist checks if the current directory exists.

Returns:

- bool: true if the current directory exists, false otherwise.

Example usage:

dir := hg.NewHDir("path/to/directory")
exists := dir.Exist()

func (*HDir) Glob

func (hd *HDir) Glob() []*HFile

Glob matches files in the current directory using the path pattern and returns a slice of HFile instances.

Returns:

- []*HFile: A slice of HFile instances representing the files that match the provided pattern in the current directory.

Example usage:

dir := hg.NewHDir("path/to/directory")
files := dir.Glob("*.txt")

func (HDir) HString

func (hd HDir) HString() HString

HString returns the HString representation of the current directory's path.

func (*HDir) Join

func (hd *HDir) Join(elem ...HString) HString

Join joins the current directory path with the given path elements, returning the joined path.

Parameters:

- elem (...HString): One or more HString values representing path elements to be joined with the current directory path.

Returns:

- HString: The resulting joined path as an HString.

Example usage:

dir := hg.NewHDir("path/to/directory")
joinedPath := dir.Join("subdir", "file.txt")

func (*HDir) Mkdir

func (hd *HDir) Mkdir(mode ...os.FileMode) *HDir

Mkdir creates a new directory with the specified mode (optional).

Parameters:

- mode (os.FileMode, optional): The file mode for the new directory. If not provided, it defaults to DirDefault (0755).

Returns:

- *HDir: A pointer to the HDir instance on which the method was called.

Example usage:

dir := hg.NewHDir("path/to/directory")
createdDir := dir.Mkdir(0755) // Optional mode argument

func (*HDir) MkdirAll

func (hd *HDir) MkdirAll(mode ...os.FileMode) *HDir

MkdirAll creates all directories along the given path, with the specified mode (optional).

Parameters:

- mode ...os.FileMode (optional): The file mode to be used when creating the directories. If not provided, it defaults to the value of DirDefault constant (0755).

Returns:

- *HDir: A pointer to the HDir instance representing the created directories.

Example usage:

dir := hg.NewHDir("path/to/directory")
dir.MkdirAll()
dir.MkdirAll(0755)

func (*HDir) Path

func (hd *HDir) Path() HString

Path returns the absolute path of the current directory.

Returns:

- HString: The absolute path of the current directory as an HString. If an error occurs while converting the path to an absolute path, the error is stored in hd.err, which can be checked using the Error() method.

Example usage:

dir := hg.NewHDir("path/to/directory")
absPath := dir.Path()

func (*HDir) ReadDir

func (hd *HDir) ReadDir() []*HFile

ReadDir reads the content of the current directory and returns a slice of HFile instances.

Returns:

- []*HFile: A slice of HFile instances representing the files and directories in the current directory.

Example usage:

dir := hg.NewHDir("path/to/directory")
files := dir.ReadDir()

func (*HDir) Rename

func (hd *HDir) Rename(newpath HString) *HDir

Rename renames the current directory to the new path.

Parameters:

- newpath HString: The new path for the directory.

Returns:

- *HDir: A pointer to the HDir instance representing the renamed directory. If an error occurs, the original HDir instance is returned with the error stored in hd.err, which can be checked using the Error() method.

Example usage:

dir := hg.NewHDir("path/to/directory")
dir.Rename("path/to/new_directory")

func (*HDir) SetPath

func (hd *HDir) SetPath(path HString) *HDir

SetPath sets the path of the current directory.

Parameters:

- path (HString): The new path to be set for the current directory.

Returns:

- *HDir: A pointer to the updated HDir instance with the new path.

Example usage:

dir := hg.NewHDir("path/to/directory")
dir.SetPath("new/path/to/directory")

type HFile

type HFile struct {
	// contains filtered or unexported fields
}

func NewHFile

func NewHFile(name HString) *HFile

NewHFile returns a new HFile instance with the given name.

func (*HFile) Append

func (hf *HFile) Append(content HString, mode ...os.FileMode) *HFile

Append appends the given content to the file, with the specified mode (optional). If no FileMode is provided, the default FileMode (0644) is used.

func (*HFile) Chmod

func (hf *HFile) Chmod(mode os.FileMode) *HFile

Chmod changes the mode of the file.

func (*HFile) Chown

func (hf *HFile) Chown(uid, gid int) *HFile

Chown changes the owner of the file.

func (*HFile) Close

func (hf *HFile) Close()

Close closes the HFile's underlying file, if it is not already closed.

func (*HFile) Copy

func (hf *HFile) Copy(dest HString, mode ...os.FileMode) *HFile

Copy copies the file to the specified destination, with the specified mode (optional). If no FileMode is provided, the default FileMode (0644) is used.

func (HFile) Error

func (hf HFile) Error() error

Error returns the latest error that occurred during an operation.

func (HFile) Exist

func (hf HFile) Exist() bool

Exist checks if the file exists.

func (HFile) Ext

func (hf HFile) Ext() HString

Ext returns the file extension.

func (HFile) File

func (hf HFile) File() *os.File

File returns the underlying *os.File instance.

func (HFile) HDir

func (hf HFile) HDir() *HDir

HDir returns the directory the file is in as an HDir instance.

func (HFile) IsDir

func (hf HFile) IsDir() bool

IsDir checks if the file is a directory.

func (*HFile) Iterator

func (hf *HFile) Iterator() *hfiter

Iterator returns a new hfiter instance that can be used to read the file line by line, word by word, rune by rune, or byte by byte.

Returns:

- *hfiter: A pointer to the new hfiter instance.

Example usage:

hf := hg.NewHFile("file.txt")
iterator := hf.Iterator() // Returns a new hfiter instance for the file

func (*HFile) MimeType

func (hf *HFile) MimeType() HString

MimeType returns the MIME type of the file as an HString.

func (HFile) ModTime

func (hf HFile) ModTime() time.Time

ModTime returns the modification time of the file.

func (HFile) Mode

func (hf HFile) Mode() fs.FileMode

Mode returns the file mode.

func (HFile) Name

func (hf HFile) Name() string

Name returns the name of the file.

func (HFile) Path

func (hf HFile) Path() HString

Path returns the absolute path of the file.

func (*HFile) Read

func (hf *HFile) Read() HString

Read reads the content of the file and returns it as an HString.

func (HFile) ReadLines

func (hf HFile) ReadLines() HSlice[HString]

ReadLines reads the file and returns its content as a slice of lines.

func (*HFile) Remove

func (hf *HFile) Remove()

Remove removes the file.

func (*HFile) Rename

func (hf *HFile) Rename(newpath HString) *HFile

Rename renames the file to the specified new path.

func (*HFile) SeekToLine

func (hf *HFile) SeekToLine(position int64, linesRead int) (int64, HString)

SeekToLine moves the file pointer to the specified line number and reads the specified number of lines from that position. The function returns the new position and a concatenation of the lines read as an HString.

Parameters:

- position int64: The starting position in the file to read from

- linesRead int: The number of lines to read.

Returns:

- int64: The new file position after reading the specified number of lines

- HString: A concatenation of the lines read as an HString.

Example usage:

hf := hg.NewHFile("file.txt")
position, content := hf.SeekToLine(0, 5) // Read 5 lines from the beginning of the file

func (HFile) Size

func (hf HFile) Size() int64

Size returns the size of the file.

func (HFile) Split

func (hf HFile) Split() (*HDir, *HFile)

Split splits the file path into its directory and file components.

func (*HFile) TempFile

func (hf *HFile) TempFile(args ...HString) *HFile

TempFile creates a new temporary file in the specified directory with the specified name pattern, and returns a pointer to the HFile. If no directory is specified, the default directory for temporary files is used. If no name pattern is specified, the default pattern "*" is used.

Parameters:

- args ...HString: A variadic parameter specifying the directory and/or name pattern for the temporary file.

Returns:

- *HFile: A pointer to the HFile representing the temporary file.

Example usage:

hf := hg.NewHFile("")
tmpfile := hf.TempFile()                     // Creates a temporary file with default settings
tmpfileWithDir := hf.TempFile("mydir")       // Creates a temporary file in "mydir" directory
tmpfileWithPattern := hf.TempFile("", "tmp") // Creates a temporary file with "tmp" pattern

func (*HFile) Write

func (hf *HFile) Write(content HString, mode ...os.FileMode) *HFile

Write writes the given content to the file, with the specified mode (optional). If no FileMode is provided, the default FileMode (0644) is used.

type HFloat

type HFloat float64

func NewHFloat

func NewHFloat(floats ...float64) HFloat

NewHFloat creates a new HFloat with the provided float64 value.

func (HFloat) Abs

func (hf HFloat) Abs() HFloat

Abs returns the absolute value of the HFloat.

func (HFloat) Add

func (hf HFloat) Add(b HFloat) HFloat

Add adds two HFloats and returns the result.

func (HFloat) BigFloat

func (hf HFloat) BigFloat() *big.Float

BigFloat returns the HFloat as a *big.Float.

func (HFloat) Bytes

func (hf HFloat) Bytes() []byte

Bytes returns the HFloat as a byte slice.

func (HFloat) Compare

func (hf HFloat) Compare(b HFloat) HInt

Compare compares two HFloats and returns an HInt.

func (HFloat) Div

func (hf HFloat) Div(b HFloat) HFloat

Div divides two HFloats and returns the result.

func (HFloat) Eq

func (hf HFloat) Eq(b HFloat) bool

Eq checks if two HFloats are equal.

func (HFloat) Float

func (hf HFloat) Float() float64

Float returns the HFloat as a float64.

func (HFloat) Gt

func (hf HFloat) Gt(b HFloat) bool

Gt checks if the HFloat is greater than the specified HFloat.

func (HFloat) HInt

func (hf HFloat) HInt() HInt

HInt returns the HFloat as an HInt.

func (HFloat) HString

func (hf HFloat) HString() HString

HString returns the HFloat as an HString.

func (HFloat) Hash

func (hf HFloat) Hash() fhash

Hash returns a fhash struct wrapping the given HFloat.

func (HFloat) Lt

func (hf HFloat) Lt(b HFloat) bool

Lt checks if the HFloat is less than the specified HFloat.

func (HFloat) Mul

func (hf HFloat) Mul(b HFloat) HFloat

Mul multiplies two HFloats and returns the result.

func (HFloat) Ne

func (hf HFloat) Ne(b HFloat) bool

Ne checks if two HFloats are not equal.

func (HFloat) Round

func (hf HFloat) Round() HInt

Round rounds the HFloat to the nearest integer and returns the result as an HInt.

func (HFloat) RoundDecimal

func (hf HFloat) RoundDecimal(precision int) HFloat

RoundDecimal rounds the HFloat value to the specified number of decimal places.

The function takes the number of decimal places (precision) as an argument and returns a new HFloat value rounded to that number of decimals. This is achieved by multiplying the HFloat value by a power of 10 equal to the desired precision, rounding the result, and then dividing the rounded result by the same power of 10.

Parameters:

- precision (int): The number of decimal places to round the HFloat value to.

Returns:

- HFloat: A new HFloat value rounded to the specified number of decimal places.

Example usage:

hf := hg.HFloat(3.14159)
rounded := hf.RoundDecimal(2) // rounded will be 3.14

func (HFloat) Sub

func (hf HFloat) Sub(b HFloat) HFloat

Sub subtracts two HFloats and returns the result.

func (HFloat) UInt64

func (hf HFloat) UInt64() uint64

UInt64 returns the HFloat as a uint64.

type HInt

type HInt int

func NewHInt

func NewHInt(ints ...int) HInt

NewHInt creates a new HInt with the provided int value.

func (HInt) Add

func (hi HInt) Add(b HInt) HInt

Add adds two HInts and returns the result.

func (HInt) Bytes

func (hi HInt) Bytes() []byte

Bytes returns the HInt as a byte slice.

func (HInt) Div

func (hi HInt) Div(b HInt) HInt

Div divides two HInts and returns the result.

func (HInt) Eq

func (hi HInt) Eq(b HInt) bool

Eq checks if two HInts are equal.

func (HInt) Gt

func (hi HInt) Gt(b HInt) bool

Gt checks if the HInt is greater than the specified HInt.

func (HInt) Gte

func (hi HInt) Gte(b HInt) bool

Gte checks if the HInt is greater than or equal to the specified HInt.

func (HInt) HFloat

func (hi HInt) HFloat() HFloat

HFloat returns the HInt as an HFloat.

func (HInt) HString

func (hi HInt) HString() HString

HString returns the HInt as an HString.

func (HInt) Hash

func (hi HInt) Hash() ihash

Hash returns a ihash struct wrapping the given HInt.

func (HInt) Int

func (hi HInt) Int() int

Int returns the HInt as an int.

func (HInt) Int16

func (hi HInt) Int16() int16

Int16 returns the HInt as an int16.

func (HInt) Int32

func (hi HInt) Int32() int32

Int32 returns the HInt as an int32.

func (HInt) Int64

func (hi HInt) Int64() int64

Int64 returns the HInt as an int64.

func (HInt) Int8

func (hi HInt) Int8() int8

Int8 returns the HInt as an int8.

func (HInt) IsNegative

func (hi HInt) IsNegative() bool

IsNegative checks if the HInt is negative.

func (HInt) IsPositive

func (hi HInt) IsPositive() bool

IsPositive checks if the HInt is positive.

func (HInt) Lt

func (hi HInt) Lt(b HInt) bool

Lt checks if the HInt is less than the specified HInt.

func (HInt) Lte

func (hi HInt) Lte(b HInt) bool

Lte checks if the HInt is less than or equal to the specified HInt.

func (HInt) Max

func (hi HInt) Max(b HInt) HInt

Max returns the maximum of two HInts.

func (HInt) Min

func (hi HInt) Min(b HInt) HInt

Min returns the minimum of two HInts.

func (HInt) Mul

func (hi HInt) Mul(b HInt) HInt

Mul multiplies two HInts and returns the result.

func (HInt) Ne

func (hi HInt) Ne(b HInt) bool

Ne checks if two HInts are not equal.

func (HInt) Random

func (hi HInt) Random() HInt

Random returns a random HInt in the range [0, hi].

func (HInt) RandomRange

func (HInt) RandomRange(min, max HInt) HInt

RandomRange returns a random HInt in the range [min, max].

func (HInt) Rem added in v1.0.11

func (hi HInt) Rem(b HInt) HInt

Rem returns the remainder of the division between the receiver and the input value.

func (HInt) Sub

func (hi HInt) Sub(b HInt) HInt

Sub subtracts two HInts and returns the result.

func (HInt) ToBinary

func (hi HInt) ToBinary() HString

ToBinary returns the HInt as a binary string.

func (HInt) ToHex

func (hi HInt) ToHex() HString

ToHex returns the HInt as a hexadecimal string.

func (HInt) ToOctal

func (hi HInt) ToOctal() HString

ToOctal returns the HInt as an octal string.

func (HInt) UInt

func (hi HInt) UInt() uint

UInt returns the HInt as a uint.

func (HInt) UInt16

func (hi HInt) UInt16() uint16

UInt16 returns the HInt as a uint16.

func (HInt) UInt32

func (hi HInt) UInt32() uint32

UInt32 returns the HInt as a uint32.

func (HInt) UInt64

func (hi HInt) UInt64() uint64

UInt64 returns the HInt as a uint64.

func (HInt) UInt8

func (hi HInt) UInt8() uint8

UInt8 returns the HInt as a uint8.

type HMap

type HMap[K comparable, V any] map[K]V

func HMapFromMap

func HMapFromMap[K comparable, V any](m map[K]V) HMap[K, V]

HMapFromMap creates an HMap from a given Go map.

func HMapOf

func HMapOf[K comparable, V any](entries ...any) HMap[K, V]

HMapOf creates an HMap from a list of alternating keys and values. The function takes a variadic parameter representing a list of alternating keys and values. The keys must be of a comparable type, while the values can be of any type. The function returns a newly created HMap containing the provided key-value pairs.

Parameters:

- entries ...any: A variadic parameter representing a list of alternating keys and values. The number of elements in this list must be even, as it should contain pairs of keys and values.

Returns:

- HMap[K, V]: A new HMap containing the provided key-value pairs.

Panics:

- If the number of elements in 'entries' is not even, as it must contain pairs of keys and values. If the provided keys and values are not of the correct types (K and V, respectively).

Example usage:

hmap := hg.HMapOf["string", int]("key1", 1, "key2", 2, "key3", 3)

func NewHMap

func NewHMap[K comparable, V any](size ...int) HMap[K, V]

NewHMap creates a new HMap of the specified size or an empty HMap if no size is provided.

func (HMap[K, V]) Clear

func (hmap HMap[K, V]) Clear() HMap[K, V]

Clear removes all key-value pairs from the HMap.

func (HMap[K, V]) Clone

func (hmap HMap[K, V]) Clone() HMap[K, V]

Clone creates a new HMap that is a copy of the original HMap.

func (HMap[K, V]) Contains

func (hmap HMap[K, V]) Contains(key K) bool

Contains checks if the HMap contains the specified key.

func (HMap[K, V]) Copy

func (hmap HMap[K, V]) Copy(src HMap[K, V]) HMap[K, V]

Copy copies the source HMap's key-value pairs to the target HMap.

func (HMap[K, V]) Delete

func (hmap HMap[K, V]) Delete(keys ...K) HMap[K, V]

Delete removes the specified keys from the HMap.

func (HMap[K, V]) Empty

func (hmap HMap[K, V]) Empty() bool

Empty checks if the HMap is empty.

func (HMap[K, V]) Eq

func (hmap HMap[K, V]) Eq(other HMap[K, V]) bool

Eq checks if two HMaps are equal.

func (HMap[K, V]) Filter

func (hmap HMap[K, V]) Filter(fn func(K, V) bool) HMap[K, V]

Filter filters the HMap based on a given function and returns a new HMap containing the matching key-value pairs. The provided function 'fn' should take a key and a value as input parameters and return a boolean value. If the function returns true, the key-value pair will be included in the resulting HMap.

Parameters:

- fn func(K, V) bool: A function that takes a key and a value as input parameters and returns a boolean value.

Returns:

- HMap[K, V]: A new HMap containing the key-value pairs for which the provided function returned true.

Example usage:

filteredHMap := originalHMap.Filter(func(key K, value V) bool {
	return value >= 10
})

func (HMap[K, V]) FilterParallel

func (hmap HMap[K, V]) FilterParallel(fn func(K, V) bool) HMap[K, V]

FilterParallel filters the HMap based on a given function in parallel and returns a new HMap containing the matching key-value pairs. The provided function 'fn' should take a key and a value as input parameters and return a boolean value. If the function returns true, the key-value pair will be included in the resulting HMap. This function is designed for better performance on large HMaps by utilizing parallel processing.

Parameters:

- fn func(K, V) bool: A function that takes a key and a value as input parameters and returns a boolean value.

Returns:

- HMap[K, V]: A new HMap containing the key-value pairs for which the provided function returned true.

Example usage:

filteredHMap := originalHMap.FilterParallel(func(key K, value V) bool {
	return value >= 10
})

TODO: написать тесты.

func (HMap[K, V]) ForEach

func (hmap HMap[K, V]) ForEach(fn func(K, V))

ForEach applies a function to each key-value pair in the HMap. The provided function 'fn' should take a key and a value as input parameters and perform an operation. This function is useful for side effects, as it does not return a new HMap.

Parameters:

- fn func(K, V): A function that takes a key and a value as input parameters and performs an operation.

Example usage:

originalHMap.ForEach(func(key K, value V) {
	fmt.Printf("Key: %v, Value: %v\n", key, value)
})

func (HMap[K, V]) Get

func (hmap HMap[K, V]) Get(k K) V

Get retrieves the value associated with the given key.

func (HMap[K, V]) GetOrDefault

func (hmap HMap[K, V]) GetOrDefault(key K, defaultValue V) V

GetOrDefault returns the value for a key. If the key does not exist, returns the default value instead. This function is useful when you want to provide a fallback value for keys that may not be present in the HMap.

Parameters:

- key K: The key for which to retrieve the value.

- defaultValue V: The default value to return if the key does not exist in the HMap.

Returns:

- V: The value associated with the key if it exists in the HMap, or the default value if the key is not found.

Example usage:

value := hmap.GetOrDefault("someKey", "defaultValue")

func (HMap[K, V]) Invert

func (hmap HMap[K, V]) Invert() HMap[any, K]

Invert inverts the keys and values of the HMap, returning a new HMap with values as keys and keys as values. Note that the inverted HMap will have 'any' as the key type, since not all value types are guaranteed to be comparable.

func (HMap[K, V]) Keys

func (hmap HMap[K, V]) Keys() HSlice[K]

Keys returns a slice of the HMap's keys.

func (HMap[K, V]) Len

func (hmap HMap[K, V]) Len() int

Len returns the number of key-value pairs in the HMap.

func (HMap[K, V]) Map

func (hmap HMap[K, V]) Map(fn func(K, V) (K, V)) HMap[K, V]

Map applies a function to each key-value pair in the HMap and returns a new HMap with the results. The provided function 'fn' should take a key and a value as input parameters and return a new key-value pair.

Parameters:

- fn func(K, V) (K, V): A function that takes a key and a value as input parameters and returns a new key-value pair.

Returns:

- HMap[K, V]: A new HMap containing the key-value pairs resulting from applying the provided function to each key-value pair in the original HMap.

Example usage:

mappedHMap := originalHMap.Map(func(key K, value V) (K, V) {
	return key, value * 2
})

func (HMap[K, V]) MapParallel

func (hmap HMap[K, V]) MapParallel(fn func(K, V) (K, V)) HMap[K, V]

MapParallel applies a function to each key-value pair in the HMap in parallel and returns a new HMap with the results. The provided function 'fn' should take a key and a value as input parameters and return a new key-value pair. This function is designed for better performance on large HMaps by utilizing parallel processing.

Parameters:

- fn func(K, V) (K, V): A function that takes a key and a value as input parameters and returns a new key-value pair.

Returns:

- HMap[K, V]: A new HMap containing the key-value pairs resulting from applying the provided function to each key-value pair in the original HMap.

Example usage:

mappedHMap := originalHMap.MapParallel(func(key K, value V) (K, V) {
	return key, value * 2
})

func (HMap[K, V]) Ne

func (hmap HMap[K, V]) Ne(other HMap[K, V]) bool

Ne checks if two HMaps are not equal.

func (HMap[K, V]) NotEmpty

func (hmap HMap[K, V]) NotEmpty() bool

NotEmpty checks if the HMap is not empty.

func (HMap[K, V]) Set

func (hmap HMap[K, V]) Set(k K, v V) HMap[K, V]

Set sets the value for the given key in the HMap.

func (HMap[K, V]) String

func (hmap HMap[K, V]) String() string

String returns a string representation of the HMap.

func (HMap[K, V]) ToMap

func (hmap HMap[K, V]) ToMap() map[K]V

ToMap converts the HMap to a regular Go map.

func (HMap[K, V]) Values

func (hmap HMap[K, V]) Values() HSlice[V]

Values returns a slice of the HMap's values.

type HMapOrd added in v1.0.18

type HMapOrd[K comparable, V any] HSlice[hMapPair[K, V]]

func HMapOrdFromHMap

func HMapOrdFromHMap[K comparable, V any](hmap HMap[K, V]) *HMapOrd[K, V]

HMapOrdFromHMap converts a standard HMap to an ordered HMap. The resulting ordered HMap will maintain the order of its key-value pairs based on the order of insertion. This function is useful when you want to create an ordered HMap from an existing HMap.

Parameters:

- hmap HMap[K, V]: The input HMap to be converted to an ordered HMap.

Returns:

- *hMapOrd[K, V]: A pointer to a new ordered HMap containing the same key-value pairs as the input HMap.

Example usage:

hmapOrd := hg.HMapOrdFromHMap[string, int](hmap)

Converts the standard HMap 'hmap' to an ordered HMap.

func HMapOrdFromMap

func HMapOrdFromMap[K comparable, V any](m map[K]V) *HMapOrd[K, V]

HMapOrdFromMap converts a standard Go map to an ordered HMap. The resulting ordered HMap will maintain the order of its key-value pairs based on the order of insertion. This function is useful when you want to create an ordered HMap from an existing Go map.

Parameters:

- m map[K]V: The input Go map to be converted to an ordered HMap.

Returns:

- *hMapOrd[K, V]: A pointer to a new ordered HMap containing the same key-value pairs as the input Go map.

Example usage:

hmapOrd := hg.HMapOrdFromMap[string, int](goMap)

Converts the standard Go map 'map[K]V' to an ordered HMap.

func NewHMapOrd

func NewHMapOrd[K comparable, V any](size ...int) *HMapOrd[K, V]

NewHMapOrd creates a new ordered HMap with the specified size (if provided). An ordered HMap is an HMap that maintains the order of its key-value pairs based on the insertion order. If no size is provided, the default size will be used.

Parameters:

- size ...int: (Optional) The initial size of the ordered HMap. If not provided, a default size will be used.

Returns:

- *hMapOrd[K, V]: A pointer to a new ordered HMap with the specified initial size (or default size if not provided).

Example usage:

hmapOrd := hg.NewHMapOrd[string, int](10)

Creates a new ordered HMap with an initial size of 10.

func (*HMapOrd[K, V]) Clear added in v1.0.18

func (hmapo *HMapOrd[K, V]) Clear() *HMapOrd[K, V]

Clear removes all key-value pairs from the ordered HMap.

func (*HMapOrd[K, V]) Clone added in v1.0.18

func (hmapo *HMapOrd[K, V]) Clone() *HMapOrd[K, V]

Clone creates a new ordered HMap with the same key-value pairs.

func (*HMapOrd[K, V]) Contains added in v1.0.18

func (hmapo *HMapOrd[K, V]) Contains(key K) bool

Contains checks if the ordered HMap contains the specified key.

func (*HMapOrd[K, V]) Copy added in v1.0.18

func (hmapo *HMapOrd[K, V]) Copy(src *HMapOrd[K, V]) *HMapOrd[K, V]

Copy copies key-value pairs from the source ordered HMap to the current ordered HMap.

func (*HMapOrd[K, V]) Delete added in v1.0.18

func (hmapo *HMapOrd[K, V]) Delete(keys ...K) *HMapOrd[K, V]

Delete removes the specified keys from the ordered HMap.

func (*HMapOrd[K, V]) Empty added in v1.0.18

func (hmapo *HMapOrd[K, V]) Empty() bool

Empty checks if the ordered HMap is empty.

func (*HMapOrd[K, V]) Eq added in v1.0.18

func (hmapo *HMapOrd[K, V]) Eq(other *HMapOrd[K, V]) bool

Eq compares the current ordered HMap to another ordered HMap and returns true if they are equal.

func (*HMapOrd[K, V]) Filter added in v1.0.18

func (hmapo *HMapOrd[K, V]) Filter(fn func(K, V) bool) *HMapOrd[K, V]

Filter filters the ordered HMap based on a provided predicate function, returning a new ordered HMap with only the key-value pairs that satisfy the predicate. The predicate function should take the key and value as input and return a boolean value. This function is useful when you want to create a new ordered HMap containing only the key-value pairs that meet certain criteria.

Parameters:

- fn func(K, V) bool: The predicate function that takes the key and value as input and returns a boolean value.

Returns:

- *hMapOrd[K, V]: A pointer to a new ordered HMap containing only the key-value pairs that satisfy the predicate.

Example usage:

hmapo.Filter(func(k string, v int) bool {
	return v > 10
})

Filters the ordered HMap to include only the key-value pairs where the value is greater than 10.

func (*HMapOrd[K, V]) ForEach added in v1.0.18

func (hmapo *HMapOrd[K, V]) ForEach(fn func(K, V))

ForEach executes a provided function for each key-value pair in the ordered HMap. This function is useful when you want to perform an operation or side effect for each key-value pair in the ordered HMap.

Parameters:

- fn func(K, V): The function to execute for each key-value pair in the ordered HMap. It takes a key (K) and a value (V) as arguments.

Example usage:

hmapo.ForEach(func(key K, value V) { fmt.Printf("Key: %v, Value: %v\n", key, value) }).

Prints each key-value pair in the ordered HMap.

func (*HMapOrd[K, V]) Get added in v1.0.18

func (hmapo *HMapOrd[K, V]) Get(key K) (V, bool)

Get retrieves the value for the specified key, along with a boolean indicating whether the key was found in the ordered HMap. This function is useful when you want to access the value associated with a key in the ordered HMap, and also check if the key exists in the map.

Parameters:

- key K: The key to search for in the ordered HMap.

Returns:

- V: The value associated with the specified key if found, or the zero value for the value type if the key is not found.

- bool: A boolean value indicating whether the key was found in the ordered HMap.

Example usage:

value, found := hmapo.Get("some_key")

Retrieves the value associated with the key "some_key" and checks if the key exists in the ordered HMap.

func (*HMapOrd[K, V]) GetOrDefault added in v1.0.18

func (hmapo *HMapOrd[K, V]) GetOrDefault(key K, defaultValue V) V

GetOrDefault returns the value for a key. If the key does not exist, returns the default value instead. This function is useful when you want to access the value associated with a key in the ordered HMap, but if the key does not exist, you want to return a specified default value.

Parameters:

- key K: The key to search for in the ordered HMap.

- defaultValue V: The default value to return if the key is not found in the ordered HMap.

Returns:

- V: The value associated with the specified key if found, or the provided default value if the key is not found.

Example usage:

value := hmapo.GetOrDefault("some_key", "default_value")

Retrieves the value associated with the key "some_key" or returns "default_value" if the key is not found.

func (*HMapOrd[K, V]) Invert added in v1.0.18

func (hmapo *HMapOrd[K, V]) Invert() *HMapOrd[any, K]

Invert inverts the key-value pairs in the ordered HMap, creating a new ordered HMap with the values as keys and the original keys as values.

func (*HMapOrd[K, V]) Keys added in v1.0.18

func (hmapo *HMapOrd[K, V]) Keys() HSlice[K]

Keys returns an HSlice containing all the keys in the ordered HMap.

func (*HMapOrd[K, V]) Len added in v1.0.18

func (hmapo *HMapOrd[K, V]) Len() int

Len returns the number of key-value pairs in the ordered HMap.

func (*HMapOrd[K, V]) Map added in v1.0.18

func (hmapo *HMapOrd[K, V]) Map(fn func(K, V) (K, V)) *HMapOrd[K, V]

Map applies a provided function to all key-value pairs in the ordered HMap and returns a new ordered HMap with the results. The provided function should take the key and value as input and return a new key-value pair as output. This function is useful when you want to transform the key-value pairs of an ordered HMap using a custom function.

Parameters:

- fn func(K, V) (K, V): The custom function that takes the key and value as input and returns a new key-value pair.

Returns:

- *hMapOrd[K, V]: A pointer to a new ordered HMap containing the key-value pairs after applying the custom function.

Example usage:

hmapo.Map(func(k string, v int) (string, int) {
	return strings.ToUpper(k), v * 2
}) // Transforms the keys to uppercase and doubles the values in the ordered HMap.

func (*HMapOrd[K, V]) Ne added in v1.0.18

func (hmapo *HMapOrd[K, V]) Ne(other *HMapOrd[K, V]) bool

Ne compares the current ordered HMap to another ordered HMap and returns true if they are not equal.

func (*HMapOrd[K, V]) NotEmpty added in v1.0.18

func (hmapo *HMapOrd[K, V]) NotEmpty() bool

NotEmpty checks if the ordered HMap is not empty.

func (*HMapOrd[K, V]) Set added in v1.0.18

func (hmapo *HMapOrd[K, V]) Set(key K, value V) *HMapOrd[K, V]

Set sets the value for the specified key in the ordered HMap.

func (*HMapOrd[K, V]) SortBy added in v1.0.18

func (hmapo *HMapOrd[K, V]) SortBy(f func(i, j int) bool) *HMapOrd[K, V]

SortBy sorts the ordered HMap by a custom comparison function. The comparison function should return true if the element at index i should be sorted before the element at index j. This function is useful when you want to sort the key-value pairs in an ordered HMap based on a custom comparison logic.

Parameters:

- f func(i, j int) bool: The custom comparison function used for sorting the ordered HMap.

Returns:

- *hMapOrd[K, V]: A pointer to the same ordered HMap, sorted according to the custom comparison function.

Example usage:

hmapo.SortBy(func(i, j int) bool { return (*hmapo)[i].Key < (*hmapo)[j].Key })
hmapo.SortBy(func(i, j int) bool { return (*hmapo)[i].Value < (*hmapo)[j].Value })

func (*HMapOrd[K, V]) String added in v1.0.18

func (hmapo *HMapOrd[K, V]) String() string

String returns a string representation of the ordered HMap.

func (*HMapOrd[K, V]) ToHMap added in v1.0.18

func (hmapo *HMapOrd[K, V]) ToHMap() HMap[K, V]

ToHMap converts the ordered HMap to a standard HMap.

func (*HMapOrd[K, V]) Values added in v1.0.18

func (hmapo *HMapOrd[K, V]) Values() HSlice[V]

Values returns an HSlice containing all the values in the ordered HMap.

type HSlice

type HSlice[T any] []T

func HSliceOf

func HSliceOf[T any](slice ...T) HSlice[T]

HSliceOf creates a new generic slice containing the provided elements.

func NewHSlice

func NewHSlice[T any](size ...int) HSlice[T]

NewHSlice creates a new HSlice of the given generic type T with the specified length and capacity. The size variadic parameter can have zero, one, or two integer values. If no values are provided, an empty HSlice with a length and capacity of 0 is returned. If one value is provided, it sets both the length and capacity of the HSlice. If two values are provided, the first value sets the length and the second value sets the capacity.

Parameters:

- size ...int: A variadic parameter specifying the length and/or capacity of the HSlice

Returns:

- HSlice[T]: A new HSlice of the specified generic type T with the given length and capacity

Example usage:

s1 := hg.NewHSlice[int]()        // Creates an empty HSlice of type int
s2 := hg.NewHSlice[int](5)       // Creates an HSlice with length and capacity of 5
s3 := hg.NewHSlice[int](3, 10)   // Creates an HSlice with length of 3 and capacity of 10

func (HSlice[T]) AddUnique

func (hsl HSlice[T]) AddUnique(elems ...T) HSlice[T]

func (*HSlice[T]) AddUniqueInPlace added in v1.0.19

func (hsl *HSlice[T]) AddUniqueInPlace(elems ...T)

AddUniqueInPlace appends unique elements from the provided arguments to the current slice.

The function iterates over the provided elements and checks if they are already present in the slice. If an element is not already present, it is appended to the slice.

Parameters:

- elems (...T): A variadic list of elements to be appended to the slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
slice.AddUniqueInPlace(3, 4, 5, 6, 7)
fmt.Println(slice)

Output: [1 2 3 4 5 6 7].

func (HSlice[T]) All

func (hsl HSlice[T]) All(fn func(T) bool) bool

All returns true if all elements in the slice satisfy the provided condition. This function is useful when you want to check if all elements in an HSlice meet a certain criteria.

Parameters:

- fn func(T) bool: A function that returns a boolean indicating whether the element satisfies the condition.

Returns:

- bool: True if all elements in the HSlice satisfy the condition, false otherwise.

Example usage:

slice := hg.HSlice[int]{2, 4, 6, 8, 10}
isEven := func(num int) bool { return num%2 == 0 }
allEven := slice.All(isEven)

The resulting allEven will be true since all elements in the slice are even.

func (HSlice[T]) Any

func (hsl HSlice[T]) Any(fn func(T) bool) bool

Any returns true if any element in the slice satisfies the provided condition. This function is useful when you want to check if at least one element in an HSlice meets a certain criteria.

Parameters:

- fn func(T) bool: A function that returns a boolean indicating whether the element satisfies the condition.

Returns:

- bool: True if at least one element in the HSlice satisfies the condition, false otherwise.

Example usage:

slice := hg.HSlice[int]{1, 3, 5, 7, 9}
isEven := func(num int) bool { return num%2 == 0 }
anyEven := slice.Any(isEven)

The resulting anyEven will be false since none of the elements in the slice are even.

func (HSlice[T]) Append

func (hsl HSlice[T]) Append(elems ...T) HSlice[T]

Append appends the provided elements to the slice and returns the modified slice.

func (*HSlice[T]) AppendInPlace added in v1.0.19

func (hsl *HSlice[T]) AppendInPlace(elems ...T)

AppendInPlace appends the provided elements to the slice and modifies the original slice.

func (HSlice[T]) Cap added in v1.0.1

func (hsl HSlice[T]) Cap() int

Cap returns the capacity of the HSlice.

func (HSlice[T]) Chunks

func (hsl HSlice[T]) Chunks(size int) []HSlice[T]

Chunks splits the HSlice into smaller chunks of the specified size. The function iterates through the HSlice, creating new HSlice[T] chunks of the specified size. If size is less than or equal to 0 or the HSlice is empty, it returns an empty slice of HSlice[T]. If size is greater than or equal to the length of the HSlice, it returns a slice of HSlice[T] containing the original HSlice.

Parameters:

- size int: The size of each chunk.

Returns:

- []HSlice[T]: A slice of HSlice[T] containing the chunks of the original HSlice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5, 6}
chunks := slice.Chunks(2)

The resulting chunks will be: [{1, 2}, {3, 4}, {5, 6}].

func (HSlice[T]) Clone

func (hsl HSlice[T]) Clone() HSlice[T]

Clone returns a copy of the slice.

func (HSlice[T]) Contains

func (hsl HSlice[T]) Contains(val T) bool

Contains returns true if the slice contains the provided value.

func (HSlice[T]) ContainsAll added in v1.0.32

func (hsl HSlice[T]) ContainsAll(other HSlice[T]) bool

ContainsAll checks if the HSlice contains all elements from another HSlice.

func (HSlice[T]) ContainsAny added in v1.0.32

func (hsl HSlice[T]) ContainsAny(other HSlice[T]) bool

ContainsAny checks if the HSlice contains any element from another HSlice.

func (HSlice[T]) Count

func (hsl HSlice[T]) Count(elem T) int

Count returns the count of the given element in the slice.

func (HSlice[T]) Counter

func (hsl HSlice[T]) Counter() *HMapOrd[any, int]

Counter returns an ordered map with the counts of each unique element in the slice. This function is useful when you want to count the occurrences of each unique element in an HSlice.

Returns:

- *hMapOrd[any, int]: An ordered HMap with keys representing the unique elements in the HSlice and values representing the counts of those elements.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 1, 2, 1}
counts := slice.Counter()
// The counts ordered HMap will contain:
// 1 -> 3 (since 1 appears three times)
// 2 -> 2 (since 2 appears two times)
// 3 -> 1 (since 3 appears once)

func (HSlice[T]) Cut

func (hsl HSlice[T]) Cut(start, end int) HSlice[T]

Cut returns a new slice that is the current slice with the elements between the specified start and end indices removed.

The function checks if the start and end indices are within the bounds of the original slice. If the end index is negative, it is added to the length of the slice to calculate the actual end index. If the start index is negative or greater than the end index, an empty slice is returned. If the end index is greater than the length of the slice, it is set to the length of the slice.

Parameters:

- start (int): The start index of the range to be removed.

- end (int): The end index of the range to be removed.

Returns:

- HSlice[T]: A new slice containing elements from the current slice with the specified range removed.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
newSlice := slice.Cut(1, 4)
fmt.Println(newSlice)

Output: [1 5].

func (HSlice[T]) Delete

func (hsl HSlice[T]) Delete(i int) HSlice[T]

Delete removes the element at the specified index from the slice and returns the modified slice.

func (*HSlice[T]) DeleteInPlace added in v1.0.19

func (hsl *HSlice[T]) DeleteInPlace(i int)

DeleteInPlace removes the element at the specified index from the slice and modifies the original slice.

func (HSlice[T]) Difference

func (hsl HSlice[T]) Difference(other HSlice[T]) HSlice[T]

Difference returns the difference between the current slice and another slice, i.e., elements present in the current slice but not in the other slice.

Parameters:

- other HSlice[T]: The other slice to calculate the difference with.

Returns:

- HSlice[T]: A new HSlice containing the difference between the two slices.

Example usage:

slice1 := hg.HSlice[int]{1, 2, 3, 4, 5}
slice2 := hg.HSlice[int]{4, 5, 6, 7, 8}
diff := slice1.Difference(slice2)

The resulting diff will be: [1, 2, 3].

func (HSlice[T]) Empty

func (hsl HSlice[T]) Empty() bool

Empty returns true if the slice is empty.

func (HSlice[T]) Enumerate

func (hsl HSlice[T]) Enumerate() HMap[int, T]

Enumerate returns a map with the index of each element as the key. This function is useful when you want to create an HMap where the keys are the indices of the elements in an HSlice, and the values are the corresponding elements.

Returns:

- HMap[int, T]: An HMap with keys representing the indices of the elements in the HSlice and values representing the corresponding elements.

Example usage:

slice := hg.HSlice[int]{10, 20, 30}
indexedMap := slice.Enumerate()
// The indexedMap HMap will contain:
// 0 -> 10 (since 10 is at index 0)
// 1 -> 20 (since 20 is at index 1)
// 2 -> 30 (since 30 is at index 2)

func (HSlice[T]) Eq

func (hsl HSlice[T]) Eq(other HSlice[T]) bool

Eq returns true if the slice is equal to the provided other slice.

func (HSlice[T]) Fill

func (hsl HSlice[T]) Fill(val T) HSlice[T]

Fill fills the slice with the specified value. This function is useful when you want to create an HSlice with all elements having the same value. This method can be used in place, as it modifies the original slice.

Parameters:

- val T: The value to fill the HSlice with.

Returns:

- HSlice[T]: A reference to the original HSlice filled with the specified value.

Example usage:

slice := hg.HSlice[int]{0, 0, 0}
slice.Fill(5)

The modified slice will now contain: 5, 5, 5.

func (HSlice[T]) Filter

func (hsl HSlice[T]) Filter(fn func(T) bool) HSlice[T]

Filter returns a new slice containing elements that satisfy a given condition.

The function takes one parameter of type T (the same type as the elements of the slice) and returns a boolean value. If the returned value is true, the element is added to a new slice, which is then returned as the result.

Parameters:

- fn (func(T) bool): The function to be applied to each element of the slice to determine if it should be included in the result.

Returns:

- HSlice[T]: A new slice containing the elements that satisfy the given condition.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
even := slice.Filter(func(val int) bool {
    return val%2 == 0
})
fmt.Println(even)

Output: [2 4].

func (*HSlice[T]) FilterInPlace added in v1.0.19

func (hsl *HSlice[T]) FilterInPlace(fn func(T) bool)

FilterInPlace removes elements from the current slice that do not satisfy a given condition.

The function takes one parameter of type T (the same type as the elements of the slice) and returns a boolean value. If the returned value is false, the element is removed from the slice.

Parameters:

- fn (func(T) bool): The function to be applied to each element of the slice to determine if it should be kept in the slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
slice.FilterInPlace(func(val int) bool {
    return val%2 == 0
})
fmt.Println(slice)

Output: [2 4].

func (HSlice[T]) FilterParallel

func (hsl HSlice[T]) FilterParallel(fn func(T) bool) HSlice[T]

FilterParallel returns a new slice containing elements that satisfy a given condition, computed in parallel.

The function iterates over the elements of the slice and applies the provided predicate function to each element. If the length of the slice is less than a predefined threshold (max), it falls back to the sequential Filter function. Otherwise, the slice is divided into two halves and the predicate function is applied to each half in parallel using goroutines. The resulting slices are then combined to form the final output slice.

Note: The order of the elements in the output slice may not be the same as the input slice due to parallel processing.

Parameters:

- fn (func(T) bool): The predicate function to be applied to each element of the slice.

Returns:

- HSlice[T]: A new slice containing the elements that satisfy the given condition.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
even := slice.FilterParallel(func(val int) bool {
    return val % 2 == 0
})
fmt.Println(even)

Output: {2 4}.

func (HSlice[T]) FilterZeroValues

func (hsl HSlice[T]) FilterZeroValues() HSlice[T]

FilterZeroValues returns a new slice with all zero values removed.

The function iterates over the elements in the slice and checks if they are zero values using the reflect.DeepEqual function. If an element is not a zero value, it is added to the resulting slice. The new slice, containing only non-zero values, is returned.

Returns:

- HSlice[T]: A new slice containing only non-zero values from the original slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 0, 4, 0}
nonZeroSlice := slice.FilterZeroValues()
fmt.Println(nonZeroSlice)

Output: [1 2 4].

func (*HSlice[T]) FilterZeroValuesInPlace added in v1.0.19

func (hsl *HSlice[T]) FilterZeroValuesInPlace()

FilterZeroValuesInPlace removes all zero values from the current slice.

The function iterates over the elements in the slice and checks if they are zero values using the reflect.DeepEqual function. If an element is a zero value, it is removed from the slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 0, 4, 0}
slice.FilterZeroValuesInPlace()
fmt.Println(slice)

Output: [1 2 4].

func (HSlice[T]) Flatten

func (hsl HSlice[T]) Flatten() HSlice[any]

Flatten flattens the nested slice structure into a single-level HSlice[any].

It recursively traverses the nested slice structure and appends all non-slice elements to a new HSlice[any].

Returns:

- HSlice[any]: A new HSlice[any] containing the flattened elements.

Example usage:

nested := hg.HSlice[any]{1, 2, hg.HSlice[int]{3, 4, 5}, []any{6, 7, []int{8, 9}}}
flattened := nested.Flatten()
fmt.Println(flattened)

Output: [1 2 3 4 5 6 7 8 9].

func (HSlice[T]) ForEach

func (hsl HSlice[T]) ForEach(fn func(T))

ForEach applies a given function to each element in the slice.

The function takes one parameter of type T (the same type as the elements of the slice). The function is applied to each element in the order they appear in the slice.

Parameters:

- fn (func(T)): The function to be applied to each element of the slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3}
slice.ForEach(func(val int) {
    fmt.Println(val * 2)
})
// Output:
// 2
// 4
// 6

func (HSlice[T]) Get

func (hsl HSlice[T]) Get(index int) T

Get returns the element at the given index, handling negative indices as counting from the end of the slice.

func (HSlice[T]) Index

func (hsl HSlice[T]) Index(val T) int

Index returns the index of the first occurrence of the specified value in the slice, or -1 if not found.

func (HSlice[T]) Insert

func (hsl HSlice[T]) Insert(i int, values ...T) HSlice[T]

Insert inserts values at the specified index in the slice and returns the resulting slice. The original slice remains unchanged.

Parameters:

- i int: The index at which to insert the new values.

- values ...T: A variadic list of values to insert at the specified index.

Returns:

- HSlice[T]: A new HSlice containing the original elements and the inserted values.

Example usage:

slice := hg.HSlice[string]{"a", "b", "c", "d"}
newSlice := slice.Insert(2, "e", "f")

The resulting newSlice will be: ["a", "b", "e", "f", "c", "d"].

func (*HSlice[T]) InsertInPlace added in v1.0.19

func (hsl *HSlice[T]) InsertInPlace(i int, values ...T)

InsertInPlace inserts values at the specified index in the slice and modifies the original slice.

Parameters:

- i int: The index at which to insert the new values.

- values ...T: A variadic list of values to insert at the specified index.

Example usage:

slice := hg.HSlice[string]{"a", "b", "c", "d"}
slice.InsertInPlace(2, "e", "f")

The resulting slice will be: ["a", "b", "e", "f", "c", "d"].

func (HSlice[T]) Intersection

func (hsl HSlice[T]) Intersection(other HSlice[T]) HSlice[T]

Intersection returns the intersection of the current slice and another slice, i.e., elements present in both slices.

Parameters:

- other HSlice[T]: The other slice to calculate the intersection with.

Returns:

- HSlice[T]: A new HSlice containing the intersection of the two slices.

Example usage:

slice1 := hg.HSlice[int]{1, 2, 3, 4, 5}
slice2 := hg.HSlice[int]{4, 5, 6, 7, 8}
intersection := slice1.Intersection(slice2)

The resulting intersection will be: [4, 5].

func (HSlice[T]) Join

func (hsl HSlice[T]) Join(sep ...T) HString

Join joins the elements in the slice into a single HString, separated by the provided separator (if any).

func (HSlice[T]) Last

func (hsl HSlice[T]) Last() T

Last returns the last element of the slice.

func (HSlice[T]) LastIndex

func (hsl HSlice[T]) LastIndex() int

LastIndex returns the last index of the slice.

func (HSlice[T]) Len

func (hsl HSlice[T]) Len() int

Len returns the length of the slice.

func (HSlice[T]) Map

func (hsl HSlice[T]) Map(fn func(T) T) HSlice[T]

Map returns a new slice by applying a given function to each element in the current slice.

The function takes one parameter of type T (the same type as the elements of the slice) and returns a value of type T. The returned value is added to a new slice, which is then returned as the result.

Parameters:

- fn (func(T) T): The function to be applied to each element of the slice.

Returns:

- HSlice[T]: A new slice containing the results of applying the function to each element of the current slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3}
doubled := slice.Map(func(val int) int {
    return val * 2
})
fmt.Println(doubled)

Output: [2 4 6].

func (*HSlice[T]) MapInPlace added in v1.0.19

func (hsl *HSlice[T]) MapInPlace(fn func(T) T)

MapInPlace applies a given function to each element in the current slice, modifying the elements in place.

The function takes one parameter of type T (the same type as the elements of the slice) and returns a value of type T. The returned value replaces the original element in the slice.

Parameters:

- fn (func(T) T): The function to be applied to each element of the slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3}
slice.MapInPlace(func(val int) int {
    return val * 2
})
fmt.Println(slice)

Output: [2 4 6].

func (HSlice[T]) MapParallel

func (hsl HSlice[T]) MapParallel(fn func(T) T) HSlice[T]

MapParallel applies a given function to each element in the slice in parallel and returns a new slice.

The function iterates over the elements of the slice and applies the provided function to each element. If the length of the slice is less than a predefined threshold (max), it falls back to the sequential Map function. Otherwise, the slice is divided into two halves and the function is applied to each half in parallel using goroutines. The resulting slices are then combined to form the final output slice.

Note: The order of the elements in the output slice may not be the same as the input slice due to parallel processing.

Parameters:

- fn (func(T) T): The function to be applied to each element of the slice.

Returns:

- HSlice[T]: A new slice with the results of applying the given function to each element of the original slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
squared := slice.MapParallel(func(val int) int {
    return val * val
})
fmt.Println(squared)

Output: {1 4 9 16 25}.

func (HSlice[T]) Max

func (hsl HSlice[T]) Max() T

Max returns the maximum element in the slice, assuming elements are comparable.

func (HSlice[T]) Min

func (hsl HSlice[T]) Min() T

Min returns the minimum element in the slice, assuming elements are comparable.

func (HSlice[T]) Ne

func (hsl HSlice[T]) Ne(other HSlice[T]) bool

Ne returns true if the slice is not equal to the provided other slice.

func (HSlice[T]) NotEmpty

func (hsl HSlice[T]) NotEmpty() bool

NotEmpty returns true if the slice is not empty.

func (HSlice[T]) Permutations

func (hsl HSlice[T]) Permutations() []HSlice[T]

Permutations returns all possible permutations of the elements in the slice.

The function uses a recursive approach to generate all the permutations of the elements. If the slice has a length of 0 or 1, it returns the slice itself wrapped in a single-element slice.

Returns:

- []HSlice[T]: A slice of HSlice[T] containing all possible permutations of the elements in the slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3}
perms := slice.Permutations()
for _, perm := range perms {
    fmt.Println(perm)
}
// Output:
// [1 2 3]
// [1 3 2]
// [2 1 3]
// [2 3 1]
// [3 1 2]
// [3 2 1]

func (HSlice[T]) Pop

func (hsl HSlice[T]) Pop() (T, HSlice[T])

Pop returns the last element of the slice and a new slice without the last element.

func (HSlice[T]) Random

func (hsl HSlice[T]) Random() T

Random returns a random element from the slice.

The function uses the crypto/rand package to generate a random index within the bounds of the slice. If the slice is empty, the zero value of type T is returned.

Returns:

- T: A random element from the slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
randomElement := slice.Random()
fmt.Println(randomElement)

Output: <any random element from the slice>.

func (HSlice[T]) RandomSample

func (hsl HSlice[T]) RandomSample(sequence int) HSlice[T]

RandomSample returns a new slice containing a random sample of elements from the original slice. The sampling is done without replacement, meaning that each element can only appear once in the result.

Parameters:

- sequence int: The number of elements to include in the random sample.

Returns:

- HSlice[T]: A new HSlice containing the random sample of elements.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5, 6, 7, 8, 9}
sample := slice.RandomSample(3)

The resulting sample will contain 3 unique elements randomly selected from the original slice.

func (HSlice[T]) Range

func (hsl HSlice[T]) Range(start, end int) HSlice[T]

Range returns a new slice containing elements from the current slice between the specified start and end indices.

The function checks if the start and end indices are within the bounds of the original slice. If the end index is negative, it is added to the length of the slice to calculate the actual end index. If the start index is negative or greater than the end index, an empty slice is returned. If the end index is greater than the length of the slice, it is set to the length of the slice.

Parameters:

- start (int): The start index of the range.

- end (int): The end index of the range.

Returns:

- HSlice[T]: A new slice containing elements from the current slice between the start and end indices.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
subSlice := slice.Range(1, 4)
fmt.Println(subSlice)

Output: [2 3 4].

func (HSlice[T]) Reduce

func (hsl HSlice[T]) Reduce(fn func(acc, val T) T, initial T) T

Reduce reduces the slice to a single value using a given function and an initial value.

The function takes two parameters of type T (the same type as the elements of the slice): an accumulator and a value from the slice. The accumulator is initialized with the provided initial value, and the function is called for each element in the slice. The returned value from the function becomes the new accumulator value for the next iteration. After processing all the elements in the slice, the final accumulator value is returned as the result.

Parameters:

- fn (func(acc, val T) T): The function to be applied to each element of the slice and the accumulator. This function should return a new value for the accumulator.

- initial (T): The initial value for the accumulator.

Returns:

- T: The final accumulator value after processing all the elements in the slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
sum := slice.Reduce(func(acc, val int) int {
    return acc + val
}, 0)
fmt.Println(sum)

Output: 15.

func (HSlice[T]) ReduceParallel

func (hsl HSlice[T]) ReduceParallel(fn func(T, T) T, initial T) T

ReduceParallel reduces the slice to a single value using a given function and an initial value, computed in parallel.

The function iterates over the elements of the slice and applies the provided reducer function to each element in a pairwise manner. If the length of the slice is less than a predefined threshold (max), it falls back to the sequential Reduce function. Otherwise, the slice is divided into two halves and the reducer function is applied to each half in parallel using goroutines. The resulting values are combined using the reducer function to produce the final output value.

Note: Due to parallel processing, the order in which the reducer function is applied to the elements may not be the same as the input slice.

Parameters:

- fn (func(T, T) T): The reducer function to be applied to each element of the slice.

- initial (T): The initial value to be used as the starting point for the reduction.

Returns:

- T: A single value obtained by applying the reducer function to the elements of the slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5}
sum := slice.ReduceParallel(func(acc, val int) int {
    return acc + val
}, 0)
fmt.Println(sum)

Output: 15.

func (HSlice[T]) Replace added in v1.0.31

func (hsl HSlice[T]) Replace(i, j int, values ...T) HSlice[T]

Replace replaces the elements of hsl[i:j] with the given values, and returns a new slice with the modifications. The original slice remains unchanged. Replace panics if hsl[i:j] is not a valid slice of hsl.

Parameters:

- i int: The starting index of the slice to be replaced.

- j int: The ending index of the slice to be replaced.

- values ...T: A variadic list of values to replace the existing slice.

Returns:

- HSlice[T]: A new HSlice containing the original elements with the specified elements replaced.

Example usage:

slice := hg.HSlice[string]{"a", "b", "c", "d"}
newSlice := slice.Replace(1, 3, "e", "f")

The original slice remains ["a", "b", "c", "d"], and the newSlice will be: ["a", "e", "f", "d"].

func (*HSlice[T]) ReplaceInPlace added in v1.0.31

func (hsl *HSlice[T]) ReplaceInPlace(i, j int, values ...T)

ReplaceInPlace replaces the elements of hsl[i:j] with the given values, and modifies the original slice in place. ReplaceInPlace panics if hsl[i:j] is not a valid slice of hsl.

Parameters:

- i int: The starting index of the slice to be replaced.

- j int: The ending index of the slice to be replaced.

- values ...T: A variadic list of values to replace the existing slice.

Example usage:

slice := hg.HSlice[string]{"a", "b", "c", "d"}
slice.ReplaceInPlace(1, 3, "e", "f")

After the ReplaceInPlace operation, the resulting slice will be: ["a", "e", "f", "d"].

func (HSlice[T]) Reverse

func (hsl HSlice[T]) Reverse() HSlice[T]

Reverse reverses the order of the elements in the slice. This method can be used in place, as it modifies the original slice.

Returns:

- HSlice[T]: The modified slice with the elements reversed.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5} reversed := slice.Reverse() fmt.Println(reversed)

Output: [5 4 3 2 1].

func (HSlice[T]) Set

func (hsl HSlice[T]) Set(i int, val T) HSlice[T]

Set sets the value at the specified index in the slice and returns the modified slice. This method can be used in place, as it modifies the original slice.

Parameters:

- i (int): The index at which to set the new value.

- val (T): The new value to be set at the specified index.

Returns:

- HSlice[T]: The modified slice with the new value set at the specified index.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5} slice.Set(2, 99) fmt.Println(slice)

Output: [1 2 99 4 5].

func (HSlice[T]) Shuffle

func (hsl HSlice[T]) Shuffle() HSlice[T]

Shuffle shuffles the elements in the slice randomly. This method can be used in place, as it modifies the original slice.

The function uses the crypto/rand package to generate random indices.

Returns:

- HSlice[T]: The modified slice with the elements shuffled randomly.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5} shuffled := slice.Shuffle() fmt.Println(shuffled)

Output: A randomly shuffled version of the original slice, e.g., [4 1 5 2 3].

func (HSlice[T]) SortBy

func (hsl HSlice[T]) SortBy(f func(i, j int) bool) HSlice[T]

SortBy sorts the elements in the slice using the provided comparison function. This method can be used in place, as it modifies the original slice.

The function takes a custom comparison function as an argument and sorts the elements of the slice using the provided logic. The comparison function should return true if the element at index i should come before the element at index j, and false otherwise.

Parameters:

- f func(i, j int) bool: A comparison function that takes two indices i and j.

Returns:

- HSlice[T]: The sorted HSlice.

Example usage:

hsl := NewHSlice[int](1, 5, 3, 2, 4) hsl.SortBy(func(i, j int) bool { return hsl[i] < hsl[j] }) // sorts in ascending order.

func (HSlice[T]) String

func (hsl HSlice[T]) String() string

String returns a string representation of the slice.

func (HSlice[T]) Swap

func (hsl HSlice[T]) Swap(i, j int) HSlice[T]

Swap swaps the elements at the specified indices in the slice and returns the modified slice. This method can be used in place, as it modifies the original slice.

Parameters:

- i (int): The index of the first element to be swapped.

- j (int): The index of the second element to be swapped.

Returns:

- HSlice[T]: The modified slice with the elements at the specified indices swapped.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 4, 5} slice.Swap(1, 3) fmt.Println(slice)

Output: [1 4 3 2 5].

func (HSlice[T]) SymmetricDifference

func (hsl HSlice[T]) SymmetricDifference(other HSlice[T]) HSlice[T]

SymmetricDifference returns the symmetric difference between the current slice and another slice, i.e., elements present in either the current slice or the other slice but not in both.

Parameters:

- other HSlice[T]: The other slice to calculate the symmetric difference with.

Returns:

- HSlice[T]: A new HSlice containing the symmetric difference between the two slices.

Example usage:

slice1 := hg.HSlice[int]{1, 2, 3, 4, 5}
slice2 := hg.HSlice[int]{4, 5, 6, 7, 8}
symDiff := slice1.SymmetricDifference(slice2)

The resulting symDiff will be: [1, 2, 3, 6, 7, 8].

func (HSlice[T]) ToHMapHashed

func (hsl HSlice[T]) ToHMapHashed() HMap[HString, T]

ToHMapHashed returns a map with the hashed version of each element as the key.

func (HSlice[T]) ToSlice

func (hsl HSlice[T]) ToSlice() []T

ToSlice returns a new slice with the same elements as the HSlice[T].

func (HSlice[T]) ToStringSlice

func (hsl HSlice[T]) ToStringSlice() []string

ToStringSlice converts the slice into a slice of strings.

func (HSlice[T]) Union

func (hsl HSlice[T]) Union(other HSlice[T]) HSlice[T]

Union returns a new slice containing the unique elements of the current slice and the provided other slice.

The order of elements in the returned slice is the same as the order in the original slices. Elements from the current slice appear first, followed by elements from the other slice.

Parameters:

- other (HSlice[T]): The other slice to create the union with.

Returns:

- HSlice[T]: A new HSlice containing the unique elements of the current slice and the provided other slice.

Example usage:

slice1 := hg.HSlice[int]{1, 2, 3}
slice2 := hg.HSlice[int]{3, 4, 5}
union := slice1.Union(slice2)

The resulting union slice will be: [1, 2, 3, 4, 5].

func (HSlice[T]) Unique

func (hsl HSlice[T]) Unique() HSlice[T]

Unique returns a new slice containing unique elements from the current slice.

The order of elements in the returned slice is the same as the order in the original slice.

Returns:

- HSlice[T]: A new HSlice containing unique elements from the current slice.

Example usage:

slice := hg.HSlice[int]{1, 2, 3, 2, 4, 5, 3}
unique := slice.Unique()

The resulting unique slice will be: [1, 2, 3, 4, 5].

func (HSlice[T]) Zip

func (hsl HSlice[T]) Zip(slices ...HSlice[T]) []HSlice[T]

Zip zips the elements of the given slices with the current slice into a new slice of HSlice[T] elements.

The function combines the elements of the current slice with the elements of the given slices by index. The length of the resulting slice of HSlice[T] elements is determined by the shortest input slice.

Params:

- slices: The slices to be zipped with the current slice.

Returns:

- []HSlice[T]: A new slice of HSlice[T] elements containing the zipped elements of the input slices.

Example usage:

slice1 := hg.HSlice[int]{1, 2, 3}
slice2 := hg.HSlice[int]{4, 5, 6}
slice3 := hg.HSlice[int]{7, 8, 9}
zipped := slice1.Zip(slice2, slice3)
for _, group := range zipped {
    fmt.Println(group)
}
// Output:
// [1 4 7]
// [2 5 8]
// [3 6 9]

type HString

type HString string

func NewHString

func NewHString(strs ...string) HString

NewHString creates a new HString from the provided string (optional).

func (HString) Add

func (hs HString) Add(hstr HString) HString

Add appends the specified HString to the current HString.

func (HString) AddPrefix

func (hs HString) AddPrefix(hstr HString) HString

AddPrefix prepends the specified HString to the current HString.

func (HString) Bytes

func (hs HString) Bytes() []byte

Bytes returns the HString as a byte slice.

func (HString) Chunks

func (hs HString) Chunks(size int) HSlice[HString]

Chunks splits the HString into chunks of the specified size.

This function iterates through the HString, creating new HString chunks of the specified size. If size is less than or equal to 0 or the HString is empty, it returns an empty HSlice[HString]. If size is greater than or equal to the length of the HString, it returns an HSlice[HString] containing the original HString.

Parameters:

- size (int): The size of the chunks to split the HString into.

Returns:

- HSlice[HString]: A slice of HString chunks of the specified size.

Example usage:

text := hg.HString("Hello, World!")
chunks := text.Chunks(4)

chunks contains {"Hell", "o, W", "orld", "!"}.

func (HString) Compare

func (hs HString) Compare(hstr HString) HInt

Compare compares two HStrings and returns an HInt indicating their relative order. The result will be 0 if hs==hstr, -1 if hs < hstr, and +1 if hs > hstr.

func (HString) Contains

func (hs HString) Contains(substr HString) bool

Contains checks if the HString contains the specified substring.

func (HString) ContainsAll added in v1.0.4

func (hs HString) ContainsAll(substrs ...HString) bool

ContainsAll checks if the given HString contains all the specified substrings.

func (HString) ContainsAny

func (hs HString) ContainsAny(substrs ...HString) bool

ContainsAny checks if the HString contains any of the specified substrings.

func (HString) ContainsAnyChars added in v1.0.4

func (hs HString) ContainsAnyChars(chars HString) bool

ContainsAnyChars checks if the HString contains any characters from the specified HString.

func (HString) ContainsRegexp added in v1.0.21

func (hs HString) ContainsRegexp(pattern *regexp.Regexp) bool

ContainsRegexp checks if the HString contains a match for the specified regular expression pattern.

func (HString) ContainsRune

func (hs HString) ContainsRune(r rune) bool

ContainsRune checks if the HString contains the specified rune.

func (HString) Count

func (hs HString) Count(substr HString) int

Count returns the number of non-overlapping instances of the substring in the HString.

func (HString) Cut

func (hs HString) Cut(start, end HString) HString

Cut returns a new HString that contains the text between the first occurrences of the 'start' and 'end' strings.

The function searches for the 'start' and 'end' strings within the HString, and if both are found, it returns a new HString containing the text between the first occurrences of 'start' and 'end'. If either 'start' or 'end' is empty or not found in the HString, it returns the original HString.

Parameters:

- start (HString): The HString marking the beginning of the text to be cut.

- end (HString): The HString marking the end of the text to be cut.

Returns:

- HString: A new HString containing the text between the first occurrences of 'start' and 'end', or the original HString if 'start' or 'end' is empty or not found.

Example usage:

hs := hg.HString("Hello, [world]! How are you?")
cut := hs.Cut("[", "]") // "world"

func (HString) Decode

func (hs HString) Decode() dec

Decode returns a dec struct wrapping the given HString.

func (HString) Empty

func (hs HString) Empty() bool

Empty checks if the HString is empty.

func (HString) Encode

func (hs HString) Encode() enc

Encode returns an enc struct wrapping the given HString.

func (HString) Eq

func (hs HString) Eq(hstr HString) bool

Eq checks if two HStrings are equal.

func (HString) EqFold added in v1.0.19

func (hs HString) EqFold(hstr HString) bool

EqFold compares two HString strings case-insensitively.

func (HString) Fields

func (hs HString) Fields() HSlice[HString]

Fields splits the HString into a slice of substrings, removing any whitespace.

func (HString) Gt

func (hs HString) Gt(hstr HString) bool

Gt checks if the HString is greater than the specified HString.

func (HString) HBytes

func (hs HString) HBytes() HBytes

HBytes returns the HString as an HBytes.

func (HString) HFloat

func (hs HString) HFloat() HFloat

HFloat tries to parse the HString as a float64 and returns an HFloat.

func (HString) HInt

func (hs HString) HInt() HInt

HInt tries to parse the HString as an int and returns an HInt.

func (HString) HasPrefix

func (hs HString) HasPrefix(prefix HString) bool

HasPrefix checks if the HString has the specified prefix.

func (HString) HasSuffix

func (hs HString) HasSuffix(suffix HString) bool

HasSuffix checks if the HString has the specified suffix.

func (HString) Hash

func (hs HString) Hash() shash

Hash returns a shash struct wrapping the given HString.

func (HString) Index

func (hs HString) Index(substr HString) int

Index returns the index of the first instance of the specified substring in the HString, or -1 if substr is not present in hs.

func (HString) IndexRune

func (hs HString) IndexRune(r rune) int

IndexRune returns the index of the first instance of the specified rune in the HString.

func (HString) IsASCII added in v1.0.15

func (hs HString) IsASCII() bool

IsASCII checks if all characters in the HString are ASCII bytes.

func (HString) IsDigit

func (hs HString) IsDigit() bool

IsDigit checks if all characters in the HString are digits.

func (HString) Len

func (hs HString) Len() int

Len returns the length of the HString.

func (HString) LenRunes

func (hs HString) LenRunes() int

LenRunes returns the number of runes in the HString.

func (HString) Lt

func (hs HString) Lt(hstr HString) bool

Lt checks if the HString is less than the specified HString.

func (HString) Map

func (hs HString) Map(fn func(rune) rune) HString

Map applies the provided function to all runes in the HString and returns the resulting HString.

func (HString) Ne

func (hs HString) Ne(hstr HString) bool

Ne checks if two HStrings are not equal.

func (HString) NormalizeNFC

func (hs HString) NormalizeNFC() HString

NormalizeNFC returns a new HString with its Unicode characters normalized using the NFC form.

func (HString) NotEmpty

func (hs HString) NotEmpty() bool

NotEmpty checks if the HString is not empty.

func (HString) Random

func (HString) Random(count int) HString

Random generates a random HString with the specified length.

This function uses a predefined set of characters (ASCII_LETTERS and DIGITS) and iterates 'count' times, appending a random character from the set to the result HString.

Parameters:

- count (int): The length of the random HString to be generated.

Returns:

- HString: A random HString with the specified length.

Example usage:

randomString := hg.HString.Random(10)

randomString contains a random HString with 10 characters.

func (HString) Reader

func (hs HString) Reader() *strings.Reader

Reader returns a *strings.Reader initialized with the content of HString.

func (HString) Repeat

func (hs HString) Repeat(count int) HString

Repeat returns a new HString consisting of the specified count of the original HString.

func (HString) Replace

func (hs HString) Replace(oldS, newS HString, n int) HString

Replace replaces the 'oldS' HString with the 'newS' HString for the specified number of occurrences.

func (HString) ReplaceAll

func (hs HString) ReplaceAll(oldS, newS HString) HString

ReplaceAll replaces all occurrences of the 'oldS' HString with the 'newS' HString.

func (HString) ReplaceNth added in v1.0.5

func (hs HString) ReplaceNth(oldS, newS HString, n int) HString

ReplaceNth returns a new HString instance with the nth occurrence of oldS replaced with newS. If there aren't enough occurrences of oldS, the original HString is returned. If n is less than -1, the original HString is also returned. If n is -1, the last occurrence of oldS is replaced with newS.

Returns:

- A new HString instance with the nth occurrence of oldS replaced with newS.

Example usage:

hs := hg.HString("The quick brown dog jumped over the lazy dog.")
result := hs.ReplaceNth("dog", "fox", 2)
fmt.Println(result)

Output: "The quick brown dog jumped over the lazy fox.".

func (HString) Reverse

func (hs HString) Reverse() HString

Reverse reverses the HString.

func (HString) Runes

func (hs HString) Runes() []rune

Runes returns the HString as a slice of runes.

func (HString) Similarity

func (hs HString) Similarity(hstr HString) HFloat

Similarity calculates the similarity between two HStrings using the Levenshtein distance algorithm and returns the similarity percentage as an HFloat.

The function compares two HStrings using the Levenshtein distance, which measures the difference between two sequences by counting the number of single-character edits required to change one sequence into the other. The similarity is then calculated by normalizing the distance by the maximum length of the two input HStrings.

Parameters:

- hstr (HString): The HString to compare with hs.

Returns:

- HFloat: The similarity percentage between the two HStrings as a value between 0 and 100.

Example usage:

hs1 := hg.HString("kitten")
hs2 := hg.HString("sitting")
similarity := hs1.Similarity(hs2) // 57.14285714285714

func (HString) Split

func (hs HString) Split(sep ...HString) HSlice[HString]

Split splits the HString by the specified separator.

func (HString) String

func (hs HString) String() string

String returns the HString as a string.

func (HString) ToLower

func (hs HString) ToLower() HString

ToLower returns the HString in lowercase.

func (HString) ToTitle

func (hs HString) ToTitle() HString

ToTitle converts the HString to title case.

func (HString) ToUpper

func (hs HString) ToUpper() HString

ToUpper returns the HString in uppercase.

func (HString) Trim

func (hs HString) Trim(cutset HString) HString

Trim trims characters in the cutset from the beginning and end of the HString.

func (HString) TrimLeft

func (hs HString) TrimLeft(cutset HString) HString

TrimLeft trims characters in the cutset from the beginning of the HString.

func (HString) TrimPrefix

func (hs HString) TrimPrefix(cutset HString) HString

TrimPrefix trims the specified prefix from the HString.

func (HString) TrimRight

func (hs HString) TrimRight(cutset HString) HString

TrimRight trims characters in the cutset from the end of the HString.

func (HString) TrimSpace

func (hs HString) TrimSpace() HString

TrimSpace trims whitespace from the beginning and end of the HString.

func (HString) TrimSuffix

func (hs HString) TrimSuffix(cutset HString) HString

TrimSuffix trims the specified suffix from the HString.

Directories

Path Synopsis
pkg
deref
Package deref provides a utility function to dereference a pointer.
Package deref provides a utility function to dereference a pointer.
iter
Package iter provides a utility function for creating a range of integers.
Package iter provides a utility function for creating a range of integers.
ref
Package ref provides a utility function for creating a pointer to a value.
Package ref provides a utility function for creating a pointer to a value.

Jump to

Keyboard shortcuts

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