g

package module
v1.1.6 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2023 License: MIT Imports: 48 Imported by: 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
	FileCreate  os.FileMode = 0o666
	DirDefault  os.FileMode = 0o755
	FullAccess  os.FileMode = 0o777

	PathSeperator = String(os.PathSeparator)
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Bytes

type Bytes []byte

Bytes is an alias for the []byte type.

func NewBytes

func NewBytes(bs ...[]byte) Bytes

NewBytes creates a new Bytes value.

func (Bytes) Add

func (bs Bytes) Add(obs Bytes) Bytes

Add appends the given Bytes to the current Bytes.

func (Bytes) AddPrefix

func (bs Bytes) AddPrefix(obs Bytes) Bytes

AddPrefix prepends the given Bytes to the current Bytes.

func (Bytes) Clone

func (bs Bytes) Clone() Bytes

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

func (Bytes) Compare

func (bs Bytes) Compare(obs Bytes) Int

Compare compares the Bytes with another Bytes and returns an Int.

func (Bytes) Contains

func (bs Bytes) Contains(obs Bytes) bool

Contains checks if the Bytes contains the specified Bytes.

func (Bytes) ContainsAll

func (bs Bytes) ContainsAll(obss ...Bytes) bool

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

func (Bytes) ContainsAny

func (bs Bytes) ContainsAny(obss ...Bytes) bool

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

func (Bytes) ContainsAnyChars

func (bs Bytes) ContainsAnyChars(chars String) bool

ContainsAnyChars checks if the given Bytes contains any characters from the input String.

func (Bytes) ContainsRune

func (bs Bytes) ContainsRune(r rune) bool

ContainsRune checks if the Bytes contains the specified rune.

func (Bytes) Count

func (bs Bytes) Count(obs Bytes) int

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

func (Bytes) Empty

func (bs Bytes) Empty() bool

Empty checks if the Bytes is empty.

func (Bytes) Eq

func (bs Bytes) Eq(obs Bytes) bool

Eq checks if the Bytes is equal to another Bytes.

func (Bytes) EqFold

func (bs Bytes) EqFold(obs Bytes) bool

EqFold compares two Bytes slices case-insensitively.

func (Bytes) FindAllRegexp

func (bs Bytes) FindAllRegexp(pattern *regexp.Regexp) Option[Slice[Bytes]]

FindAllRegexp searches the Bytes for all occurrences of the regular expression pattern and returns an Option[Slice[Bytes]] containing a slice of matched substrings. If no matches are found, the Option[Slice[Bytes]] will be None.

func (Bytes) FindAllRegexpN

func (bs Bytes) FindAllRegexpN(pattern *regexp.Regexp, n Int) Option[Slice[Bytes]]

FindAllRegexpN searches the Bytes for up to n occurrences of the regular expression pattern and returns an Option[Slice[Bytes]] containing a slice of matched substrings. If no matches are found, the Option[Slice[Bytes]] will be None. If n is negative, all occurrences will be returned.

func (Bytes) FindAllSubmatchRegexp

func (bs Bytes) FindAllSubmatchRegexp(pattern *regexp.Regexp) Option[Slice[Slice[Bytes]]]

FindAllSubmatchRegexp searches the Bytes for all occurrences of the regular expression pattern and returns an Option[Slice[Slice[Bytes]]] containing the matched substrings and submatches. The Option[Slice[Slice[Bytes]]] will contain an Slice[Bytes] for each match, where each Slice[Bytes] will contain the full match at index 0, followed by any captured submatches. If no match is found, the Option[Slice[Slice[Bytes]]] will be None. This method is equivalent to calling SubmatchAllRegexpN with n = -1, which means it finds all occurrences.

func (Bytes) FindAllSubmatchRegexpN

func (bs Bytes) FindAllSubmatchRegexpN(pattern *regexp.Regexp, n Int) Option[Slice[Slice[Bytes]]]

FindAllSubmatchRegexpN searches the Bytes for occurrences of the regular expression pattern and returns an Option[Slice[Slice[Bytes]]] containing the matched substrings and submatches. The Option[Slice[Slice[Bytes]]] will contain an Slice[Bytes] for each match, where each Slice[Bytes] will contain the full match at index 0, followed by any captured submatches. If no match is found, the Option[Slice[Slice[Bytes]]] will be None. The 'n' parameter specifies the maximum number of matches to find. If n is negative, it finds all occurrences.

func (Bytes) FindRegexp

func (bs Bytes) FindRegexp(pattern *regexp.Regexp) Option[Bytes]

FindRegexp searches the Bytes for the first occurrence of the regular expression pattern and returns an Option[Bytes] containing the matched substring. If no match is found, the Option[Bytes] will be None.

func (Bytes) FindSubmatchRegexp

func (bs Bytes) FindSubmatchRegexp(pattern *regexp.Regexp) Option[Slice[Bytes]]

FindSubmatchRegexp searches the Bytes for the first occurrence of the regular expression pattern and returns an Option[Slice[Bytes]] containing the matched substrings and submatches. The Option[Slice[Bytes]] will contain an Slice[Bytes] for each match, where each Slice[Bytes] will contain the full match at index 0, followed by any captured submatches. If no match is found, the Option[Slice[Bytes]] will be None.

func (Bytes) Gt

func (bs Bytes) Gt(obs Bytes) bool

Gt checks if the Bytes is greater than another Bytes.

func (Bytes) Hash

func (bs Bytes) Hash() bhash

Hash returns a bhash struct wrapping the given Bytes.

func (Bytes) Index

func (bs Bytes) Index(obs Bytes) int

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

func (Bytes) IndexByte

func (bs Bytes) IndexByte(b byte) int

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

func (Bytes) IndexRegexp

func (bs Bytes) IndexRegexp(pattern *regexp.Regexp) Option[Slice[Int]]

IndexRegexp searches for the first occurrence of the regular expression pattern in the Bytes. If a match is found, it returns an Option containing an Slice with the start and end indices of the match. If no match is found, it returns None.

func (Bytes) IndexRune

func (bs Bytes) IndexRune(r rune) int

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

func (Bytes) LastIndex

func (bs Bytes) LastIndex(obs Bytes) int

LastIndex returns the index of the last instance of obs in bs, or -1 if obs is not present in bs.

func (Bytes) LastIndexByte

func (bs Bytes) LastIndexByte(b byte) int

LastIndexByte returns the index of the last instance of the byte b in bs, or -1 if b is not present in bs.

func (Bytes) Len

func (bs Bytes) Len() int

Len returns the length of the Bytes.

func (Bytes) LenRunes

func (bs Bytes) LenRunes() int

LenRunes returns the number of runes in the Bytes.

func (Bytes) Lower added in v1.0.6

func (bs Bytes) Lower() Bytes

Lower converts the Bytes to lowercase.

func (Bytes) Lt

func (bs Bytes) Lt(obs Bytes) bool

Lt checks if the Bytes is less than another Bytes.

func (Bytes) Map

func (bs Bytes) Map(fn func(rune) rune) Bytes

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

func (Bytes) Ne

func (bs Bytes) Ne(obs Bytes) bool

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

func (Bytes) NormalizeNFC

func (bs Bytes) NormalizeNFC() Bytes

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

func (Bytes) NotEmpty

func (bs Bytes) NotEmpty() bool

NotEmpty checks if the Bytes is not empty.

func (Bytes) Print

func (bs Bytes) Print() Bytes

Print prints the content of the Bytes to the standard output (console) and returns the Bytes unchanged.

func (Bytes) Reader

func (bs Bytes) Reader() *bytes.Reader

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

func (Bytes) Repeat

func (bs Bytes) Repeat(count int) Bytes

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

func (Bytes) Replace

func (bs Bytes) Replace(oldB, newB Bytes, n int) Bytes

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

func (Bytes) ReplaceAll

func (bs Bytes) ReplaceAll(oldB, newB Bytes) Bytes

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

func (Bytes) ReplaceRegexp

func (bs Bytes) ReplaceRegexp(pattern *regexp.Regexp, newB Bytes) Bytes

ReplaceRegexp replaces all occurrences of the regular expression matches in the Bytes with the provided newB and returns the resulting Bytes after the replacement.

func (Bytes) Reverse

func (bs Bytes) Reverse() Bytes

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

func (Bytes) Split

func (bs Bytes) Split(sep ...Bytes) Slice[Bytes]

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

func (Bytes) Std

func (bs Bytes) Std() []byte

Std returns the Bytes as a byte slice.

func (Bytes) Title added in v1.0.6

func (bs Bytes) Title() Bytes

Title converts the Bytes to title case.

func (Bytes) ToRunes

func (bs Bytes) ToRunes() []rune

ToRunes returns the Bytes as a slice of runes.

func (Bytes) ToString

func (bs Bytes) ToString() String

ToString returns the Bytes as an String.

func (Bytes) Trim

func (bs Bytes) Trim(cutset String) Bytes

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

func (Bytes) TrimLeft

func (bs Bytes) TrimLeft(cutset String) Bytes

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

func (Bytes) TrimPrefix

func (bs Bytes) TrimPrefix(cutset Bytes) Bytes

TrimPrefix trims the specified Bytes prefix from the Bytes.

func (Bytes) TrimRight

func (bs Bytes) TrimRight(cutset String) Bytes

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

func (Bytes) TrimSpace

func (bs Bytes) TrimSpace() Bytes

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

func (Bytes) TrimSuffix

func (bs Bytes) TrimSuffix(cutset Bytes) Bytes

TrimSuffix trims the specified Bytes suffix from the Bytes.

func (Bytes) Upper added in v1.0.6

func (bs Bytes) Upper() Bytes

Upper converts the Bytes to uppercase.

type Dir

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

Dir is a struct representing a directory path.

func NewDir

func NewDir(path String) *Dir

NewDir returns a new Dir instance with the given path.

func (*Dir) Chown added in v1.0.4

func (d *Dir) Chown(uid, gid int) Result[*Dir]

func (*Dir) Copy added in v1.1.0

func (d *Dir) Copy(dest String) Result[*Dir]

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

Parameters:

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

Returns:

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

Example usage:

sourceDir := g.NewDir("path/to/source")
destinationDir := sourceDir.Copy("path/to/destination")

func (*Dir) Create added in v1.1.0

func (d *Dir) Create(mode ...os.FileMode) Result[*Dir]

Create 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:

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

Example usage:

dir := g.NewDir("path/to/directory")
createdDir := dir.Create(0755) // Optional mode argument

func (*Dir) CreateAll added in v1.1.0

func (d *Dir) CreateAll(mode ...os.FileMode) Result[*Dir]

CreateAll 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:

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

Example usage:

dir := g.NewDir("path/to/directory")
dir.CreateAll()
dir.CreateAll(0755)

func (*Dir) CreateTemp added in v1.1.0

func (*Dir) CreateTemp(args ...String) Result[*Dir]

CreateTemp creates a new temporary directory in the specified directory with the specified name pattern and returns a Result, which contains a pointer to the Dir or an error if the operation fails. If no directory is specified, the default directory for temporary directories is used. If no name pattern is specified, the default pattern "*" is used.

Parameters:

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

Returns:

- *Dir: A pointer to the Dir representing the temporary directory.

Example usage:

d := g.NewDir("") tmpdir := d.CreateTemp() // Creates a temporary directory with default settings tmpdirWithDir := d.CreateTemp("mydir") // Creates a temporary directory in "mydir" directory tmpdirWithPattern := d.CreateTemp("", "tmp") // Creates a temporary directory with "tmp" pattern

func (Dir) Exist

func (d Dir) Exist() bool

Exist checks if the current directory exists.

Returns:

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

Example usage:

dir := g.NewDir("path/to/directory")
exists := dir.Exist()

func (*Dir) Glob

func (d *Dir) Glob(fullPath ...bool) Result[Slice[*File]]

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

Returns:

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

Example usage:

dir := g.NewDir("path/to/directory/*.txt")
files := dir.Glob()

func (*Dir) Join

func (d *Dir) Join(elem ...String) Result[String]

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

Parameters:

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

Returns:

- String: The resulting joined path as an String.

Example usage:

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

func (*Dir) Move

func (d *Dir) Move(newpath String) Result[*Dir]

Move function simply calls Dir.Rename

func (*Dir) Path

func (d *Dir) Path() Result[String]

Path returns the absolute path of the current directory.

Returns:

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

Example usage:

dir := g.NewDir("path/to/directory")
absPath := dir.Path()

func (*Dir) Print

func (d *Dir) Print() *Dir

Print prints the content of the Dir to the standard output (console) and returns the Dir unchanged.

func (*Dir) Read added in v1.1.0

func (d *Dir) Read(fullPath ...bool) Result[Slice[*File]]

Read reads the content of the current directory and returns a slice of File instances.

Returns:

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

Example usage:

dir := g.NewDir("path/to/directory")
files := dir.Read()

func (*Dir) Remove added in v1.0.3

func (d *Dir) Remove() Result[*Dir]

Remove attempts to delete the directory and its contents. It returns a Result, which contains either the *Dir or an error. If the directory does not exist, Remove returns a successful Result with *Dir set. Any error that occurs during removal will be of type *PathError.

func (*Dir) Rename

func (d *Dir) Rename(newpath String) Result[*Dir]

Rename renames the current directory to the new path.

Parameters:

- newpath String: The new path for the directory.

Returns:

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

Example usage:

dir := g.NewDir("path/to/directory")
dir.Rename("path/to/new_directory")

func (*Dir) SetPath

func (d *Dir) SetPath(path String) *Dir

SetPath sets the path of the current directory.

Parameters:

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

Returns:

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

Example usage:

dir := g.NewDir("path/to/directory")
dir.SetPath("new/path/to/directory")

func (*Dir) Temp added in v1.1.0

func (*Dir) Temp() *Dir

Temp returns the default directory to use for temporary files.

On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.

The directory is neither guaranteed to exist nor have accessible permissions.

func (Dir) ToString

func (d Dir) ToString() String

ToString returns the String representation of the current directory's path.

type File

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

File is a struct that represents a file along with an iterator for reading lines.

func NewFile

func NewFile(name String) *File

NewFile returns a new File instance with the given name.

func (*File) Append

func (f *File) Append(content String, mode ...os.FileMode) Result[*File]

Append appends the given content to the file, with the specified mode (optional). If no FileMode is provided, the default FileMode (0644) is used. Don't forget to close the file!

func (*File) Chmod

func (f *File) Chmod(mode os.FileMode) Result[*File]

Chmod changes the mode of the file.

func (*File) Chown

func (f *File) Chown(uid, gid int) Result[*File]

Chown changes the owner of the file.

func (*File) Close

func (f *File) Close() error

Close closes the File and unlocks its underlying file, if it is not already closed.

func (*File) Copy

func (f *File) Copy(dest String, mode ...os.FileMode) Result[*File]

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

func (*File) Create added in v1.0.9

func (f *File) Create() Result[*File]

Create is similar to os.Create, but it returns a write-locked file. Don't forget to close the file!

func (*File) CreateTemp added in v1.1.0

func (*File) CreateTemp(args ...String) Result[*File]

CreateTemp creates a new temporary file in the specified directory with the specified name pattern and returns a Result, which contains a pointer to the File or an error if the operation fails. 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 ...String: A variadic parameter specifying the directory and/or name pattern for the temporary file.

Returns:

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

Example usage:

f := g.NewFile("")
tmpfile := f.CreateTemp()                     // Creates a temporary file with default settings
tmpfileWithDir := f.CreateTemp("mydir")       // Creates a temporary file in "mydir" directory
tmpfileWithPattern := f.CreateTemp("", "tmp") // Creates a temporary file with "tmp" pattern

func (*File) Dec added in v1.0.12

func (f *File) Dec() fdec

Dec returns an fdec struct wrapping the given file for decoding.

func (*File) Dir

func (f *File) Dir() Result[*Dir]

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

func (*File) Enc added in v1.0.12

func (f *File) Enc() fenc

Enc returns an fenc struct wrapping the given file for encoding.

func (*File) Exist

func (f *File) Exist() bool

Exist checks if the file exists.

func (*File) Ext

func (f *File) Ext() String

Ext returns the file extension.

func (*File) Iterator

func (f *File) Iterator() Result[*fiter]

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

Returns:

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

Example usage:

f := g.NewFile("file.txt")
iterator := f.Iterator().Must() // Returns a new fiter instance for the file

func (*File) MimeType

func (f *File) MimeType() Result[String]

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

func (*File) Move

func (f *File) Move(newpath String) Result[*File]

Move function simply calls File.Rename

func (*File) Name

func (f *File) Name() String

Name returns the name of the file.

func (*File) Open added in v1.0.9

func (f *File) Open() Result[*File]

Open is like os.Open, but returns a read-locked file. Don't forget to close the file!

func (*File) OpenFile added in v1.0.9

func (f *File) OpenFile(flag int, perm fs.FileMode) Result[*File]

OpenFile is like os.OpenFile, but returns a locked file. If flag includes os.O_WRONLY or os.O_RDWR, the file is write-locked otherwise, it is read-locked. Don't forget to close the file!

func (*File) Path

func (f *File) Path() Result[String]

Path returns the absolute path of the file.

func (*File) Print

func (f *File) Print() *File

Print prints the content of the File to the standard output (console) and returns the File unchanged.

func (*File) Read

func (f *File) Read() Result[String]

Read opens the named file with a read-lock and returns its contents.

func (*File) ReadLines

func (f *File) ReadLines() Result[Slice[String]]

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

func (*File) Remove

func (f *File) Remove() Result[*File]

Remove removes the file.

func (*File) Rename

func (f *File) Rename(newpath String) Result[*File]

Rename renames the file to the specified new path.

func (*File) SeekToLine

func (f *File) SeekToLine(position int64, linesRead int) (int64, String)

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 String.

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

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

Example usage:

f := g.NewFile("file.txt")
position, content := f.SeekToLine(0, 5) // Read 5 lines from the beginning of the file

func (*File) Split

func (f *File) Split() (*Dir, *File)

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

func (*File) Stat

func (f *File) Stat() Result[fs.FileInfo]

Stat returns the fs.FileInfo of the file. It calls the file's Stat method if the file is open, or os.Stat otherwise.

func (*File) Std added in v1.0.10

func (f *File) Std() *os.File

Std returns the underlying *os.File instance. Don't forget to close the file with g.File().Close()!

func (*File) Unlock added in v1.0.8

func (f *File) Unlock() error

Unlock releases the file lock, allowing other processes or goroutines to access the file.

func (*File) Write

func (f *File) Write(content String, mode ...os.FileMode) Result[*File]

Write opens the named file (creating it with the given permissions if needed), then write-locks it and overwrites it with the given content.

func (*File) WriteFromReader

func (f *File) WriteFromReader(scr io.Reader, mode ...os.FileMode) Result[*File]

WriteFromReader takes an io.Reader (scr) as input and writes the data from the reader into the file. If no FileMode is provided, the default FileMode (0644) is used.

type Float

type Float float64

Float is an alias for the float64 type.

func NewFloat

func NewFloat(float float64) Float

NewFloat creates a new Float with the provided float64 value.

func (Float) Abs

func (f Float) Abs() Float

Abs returns the absolute value of the Float.

func (Float) Add

func (f Float) Add(b Float) Float

Add adds two Floats and returns the result.

func (Float) AsFloat32

func (f Float) AsFloat32() float32

AsFloat32 returns the Float as a float32.

func (Float) Bytes

func (f Float) Bytes() Bytes

Bytes returns the Float as a byte slice.

func (Float) Compare

func (f Float) Compare(b Float) Int

Compare compares two Floats and returns an Int.

func (Float) Div

func (f Float) Div(b Float) Float

Div divides two Floats and returns the result.

func (Float) Eq

func (f Float) Eq(b Float) bool

Eq checks if two Floats are equal.

func (Float) Gt

func (f Float) Gt(b Float) bool

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

func (Float) Hash

func (f Float) Hash() fhash

Hash returns a fhash struct wrapping the given Float.

func (Float) Lt

func (f Float) Lt(b Float) bool

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

func (Float) Max

func (f Float) Max(b ...Float) Float

Max returns the maximum of two Floats.

func (Float) Min

func (f Float) Min(b ...Float) Float

Min returns the minimum of two Floats.

func (Float) Mul

func (f Float) Mul(b Float) Float

Mul multiplies two Floats and returns the result.

func (Float) Ne

func (f Float) Ne(b Float) bool

Ne checks if two Floats are not equal.

func (Float) Print

func (f Float) Print() Float

Print prints the value of the Float to the standard output (console) and returns the Float unchanged.

func (Float) Round

func (f Float) Round() Int

Round rounds the Float to the nearest integer and returns the result as an Int.

func (Float) RoundDecimal

func (f Float) RoundDecimal(precision int) Float

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

The function takes the number of decimal places (precision) as an argument and returns a new Float value rounded to that number of decimals. This is achieved by multiplying the Float 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 Float value to.

Returns:

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

Example usage:

f := g.Float(3.14159)
rounded := f.RoundDecimal(2) // rounded will be 3.14

func (Float) Std

func (f Float) Std() float64

Std returns the Float as a float64.

func (Float) Sub

func (f Float) Sub(b Float) Float

Sub subtracts two Floats and returns the result.

func (Float) ToBigFloat

func (f Float) ToBigFloat() *big.Float

ToBigFloat returns the Float as a *big.Float.

func (Float) ToInt

func (f Float) ToInt() Int

ToInt returns the Float as an Int.

func (Float) ToString

func (f Float) ToString() String

ToString returns the Float as an String.

func (Float) ToUInt64

func (f Float) ToUInt64() uint64

ToUInt64 returns the Float as a uint64.

type Int

type Int int

Int is an alias for the int type.

func NewInt

func NewInt(i int) Int

NewInt creates a new Int with the provided int value.

func (Int) Abs

func (i Int) Abs() Int

Abs returns the absolute value of the Int.

func (Int) Add

func (i Int) Add(b Int) Int

Add adds two Ints and returns the result.

func (Int) AsInt16

func (i Int) AsInt16() int16

AsInt16 returns the Int as an int16.

func (Int) AsInt32

func (i Int) AsInt32() int32

AsInt32 returns the Int as an int32.

func (Int) AsInt64

func (i Int) AsInt64() int64

AsInt64 returns the Int as an int64.

func (Int) AsInt8

func (i Int) AsInt8() int8

AsInt8 returns the Int as an int8.

func (Int) AsUInt

func (i Int) AsUInt() uint

AsUInt returns the Int as a uint.

func (Int) AsUInt16

func (i Int) AsUInt16() uint16

AsUInt16 returns the Int as a uint16.

func (Int) AsUInt32

func (i Int) AsUInt32() uint32

AsUInt32 returns the Int as a uint32.

func (Int) AsUInt64

func (i Int) AsUInt64() uint64

AsUInt64 returns the Int as a uint64.

func (Int) AsUInt8

func (i Int) AsUInt8() uint8

AsUInt8 returns the Int as a uint8.

func (Int) Bytes

func (i Int) Bytes() Bytes

Bytes returns the Int as a byte slice.

func (Int) Div

func (i Int) Div(b Int) Int

Div divides two Ints and returns the result.

func (Int) Eq

func (i Int) Eq(b Int) bool

Eq checks if two Ints are equal.

func (Int) Gt

func (i Int) Gt(b Int) bool

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

func (Int) Gte

func (i Int) Gte(b Int) bool

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

func (Int) Hash

func (i Int) Hash() ihash

Hash returns a ihash struct wrapping the given Int.

func (Int) IsNegative

func (i Int) IsNegative() bool

IsNegative checks if the Int is negative.

func (Int) IsPositive

func (i Int) IsPositive() bool

IsPositive checks if the Int is positive.

func (Int) Lt

func (i Int) Lt(b Int) bool

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

func (Int) Lte

func (i Int) Lte(b Int) bool

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

func (Int) Max

func (i Int) Max(b ...Int) Int

Max returns the maximum of Ints.

func (Int) Min

func (i Int) Min(b ...Int) Int

Min returns the minimum of Ints.

func (Int) Mul

func (i Int) Mul(b Int) Int

Mul multiplies two Ints and returns the result.

func (Int) Ne

func (i Int) Ne(b Int) bool

Ne checks if two Ints are not equal.

func (Int) Print

func (i Int) Print() Int

Print prints the value of the Int to the standard output (console) and returns the Int unchanged.

func (Int) Random

func (i Int) Random() Int

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

func (Int) RandomRange

func (Int) RandomRange(from, to Int) Int

RandomRange returns a random Int in the range [from, to].

func (Int) Rem

func (i Int) Rem(b Int) Int

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

func (Int) Std

func (i Int) Std() int

Std returns the Int as an int.

func (Int) Sub

func (i Int) Sub(b Int) Int

Sub subtracts two Ints and returns the result.

func (Int) ToBigInt

func (i Int) ToBigInt() *big.Int

ToBigInt returns the Int as a *big.Int.

func (Int) ToBinary

func (i Int) ToBinary() String

ToBinary returns the Int as a binary string.

func (Int) ToFloat

func (i Int) ToFloat() Float

ToFloat returns the Int as an Float.

func (Int) ToHex

func (i Int) ToHex() String

ToHex returns the Int as a hexadecimal string.

func (Int) ToOctal

func (i Int) ToOctal() String

ToOctal returns the Int as an octal string.

func (Int) ToString

func (i Int) ToString() String

ToString returns the Int as an String.

type Map

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

Map is a generic alias for a map.

func MapFromStd

func MapFromStd[K comparable, V any](stdmap map[K]V) Map[K, V]

MapFromStd creates an Map from a given Go map.

func NewMap

func NewMap[K comparable, V any](size ...int) Map[K, V]

NewMap creates a new Map of the specified size or an empty Map if no size is provided.

func (Map[K, V]) Clear

func (m Map[K, V]) Clear() Map[K, V]

Clear removes all key-value pairs from the Map.

func (Map[K, V]) Clone

func (m Map[K, V]) Clone() Map[K, V]

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

func (Map[K, V]) Contains

func (m Map[K, V]) Contains(key K) bool

Contains checks if the Map contains the specified key.

func (Map[K, V]) Copy

func (m Map[K, V]) Copy(src Map[K, V]) Map[K, V]

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

func (Map[K, V]) Delete

func (m Map[K, V]) Delete(keys ...K) Map[K, V]

Delete removes the specified keys from the Map.

func (Map[K, V]) Empty

func (m Map[K, V]) Empty() bool

Empty checks if the Map is empty.

func (Map[K, V]) Eq

func (m Map[K, V]) Eq(other Map[K, V]) bool

Eq checks if two Maps are equal.

func (Map[K, V]) Filter

func (m Map[K, V]) Filter(fn func(K, V) bool) Map[K, V]

Filter filters the Map based on a given function and returns a new Map 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 Map.

Parameters:

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

Returns:

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

Example usage:

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

func (Map[K, V]) FilterParallel

func (m Map[K, V]) FilterParallel(fn func(K, V) bool) Map[K, V]

FilterParallel filters the Map based on a given function in parallel and returns a new Map 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 Map. This function is designed for better performance on large Maps 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:

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

Example usage:

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

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

func (Map[K, V]) ForEach

func (m Map[K, V]) ForEach(fn func(K, V))

ForEach applies a function to each key-value pair in the Map. 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 Map.

Parameters:

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

Example usage:

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

func (Map[K, V]) Get

func (m Map[K, V]) Get(k K) V

Get retrieves the value associated with the given key.

func (Map[K, V]) GetOrDefault

func (m Map[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 Map.

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 Map.

Returns:

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

Example usage:

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

func (Map[K, V]) GetOrSet

func (m Map[K, V]) GetOrSet(key K, defaultValue V) V

GetOrSet returns the value for a key. If the key exists in the Map, it returns the associated value. If the key does not exist, it sets the key to the provided default value and returns that value. This function is useful when you want to both retrieve and potentially set a default value for keys that may or may not be present in the Map.

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 Map. If the key is not found, this default value will also be set for the key in the Map.

Returns:

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

Eaxmple usage:

// Create a new ordered Map called "gos" with string keys and integer pointers as values
gos := g.NewMap[string, *int]()

// Use GetOrSet to set the value for the key "root" to 3 if it doesn't exist,
// and then print whether the value is equal to 3.
gos.GetOrSet("root", ref.Of(3))
fmt.Println(*gos.Get("root") == 3) // Should print "true"

// Use GetOrSet to retrieve the value for the key "root" (which is 3), multiply it by 2,
// and then print whether the value is equal to 6.
*gos.GetOrSet("root", ref.Of(10)) *= 2
fmt.Println(*gos.Get("root") == 6) // Should print "true"

In this example, you first create an ordered Map "gos" with string keys and integer pointers as values. Then, you use GetOrSet to set and retrieve values for the key "root" with default values of 3 and perform multiplication operations, demonstrating the behavior of GetOrSet.

func (Map[K, V]) Invert

func (m Map[K, V]) Invert() Map[any, K]

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

func (Map[K, V]) Keys

func (m Map[K, V]) Keys() Slice[K]

Keys returns a slice of the Map's keys.

func (Map[K, V]) Len

func (m Map[K, V]) Len() int

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

func (Map[K, V]) Map

func (m Map[K, V]) Map(fn func(K, V) (K, V)) Map[K, V]

Map applies a function to each key-value pair in the Map and returns a new Map 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:

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

Example usage:

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

func (Map[K, V]) MapParallel

func (m Map[K, V]) MapParallel(fn func(K, V) (K, V)) Map[K, V]

MapParallel applies a function to each key-value pair in the Map in parallel and returns a new Map 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 Maps 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:

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

Example usage:

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

func (Map[K, V]) Ne

func (m Map[K, V]) Ne(other Map[K, V]) bool

Ne checks if two Maps are not equal.

func (Map[K, V]) NotEmpty

func (m Map[K, V]) NotEmpty() bool

NotEmpty checks if the Map is not empty.

func (Map[K, V]) Print

func (m Map[K, V]) Print() Map[K, V]

Print prints the key-value pairs of the Map to the standard output (console) and returns the Map unchanged.

func (Map[K, V]) Random added in v1.1.1

func (m Map[K, V]) Random() Map[K, V]

Random returns a new map containing a single randomly selected key-value pair from the original map.

Parameters:

None.

Returns:

- Map[K, V]: A new Map containing a single randomly selected key-value pair.

Example usage:

myMap := g.Map[string, int]{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}
randomMap := myMap.Random()

The resulting map will contain one randomly selected key-value pair from the original map.

func (Map[K, V]) RandomRange added in v1.1.1

func (m Map[K, V]) RandomRange(from, to int) Map[K, V]

RandomRange returns a new map containing a random range of key-value pairs from the original map.

Parameters:

- from int: The starting index of the range (inclusive). - to int: The ending index of the range (exclusive).

Returns:

- Map[K, V]: A new Map containing a random range of key-value pairs from the specified subrange.

Example usage:

myMap := g.Map[string, int]{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}
subrangeMap := myMap.RandomRange(1, 4)

The resulting map will contain a random range of key-value pairs from index 1 (inclusive) to 4 (exclusive) of the original map.

func (Map[K, V]) RandomSample added in v1.1.1

func (m Map[K, V]) RandomSample(sequence int) Map[K, V]

RandomSample returns a new map containing a random sample of key-value pairs from the original map.

Parameters:

- sequence int: The number of unique key-value pairs to include in the random sample.

Returns:

- Map[K, V]: A new Map containing a random sample of unique key-value pairs.

Example usage:

myMap := g.Map[string, int]{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}
sampledMap := myMap.RandomSample(3)

The resulting map will contain 3 unique key-value pairs randomly selected from the original map.

func (Map[K, V]) Set

func (m Map[K, V]) Set(k K, v V) Map[K, V]

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

func (Map[K, V]) Std

func (m Map[K, V]) Std() map[K]V

Std converts the Map to a regular Go map.

func (Map[K, V]) String

func (m Map[K, V]) String() string

String returns a string representation of the Map.

func (Map[K, V]) Values

func (m Map[K, V]) Values() Slice[V]

Values returns a slice of the Map's values.

type MapOrd

type MapOrd[K comparable, V any] Slice[mapPair[K, V]]

MapOrd is a generic alias for a slice of ordered key-value pairs.

func MapOrdFromMap

func MapOrdFromMap[K comparable, V any](m Map[K, V]) *MapOrd[K, V]

MapOrdFromMap converts a standard Map to an ordered Map. The resulting ordered Map 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 Map from an existing Map.

Parameters:

- m Map[K, V]: The input Map to be converted to an ordered Map.

Returns:

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

Example usage:

mapOrd := g.MapOrdFromMap[string, int](hmap)

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

func MapOrdFromStd

func MapOrdFromStd[K comparable, V any](m map[K]V) *MapOrd[K, V]

MapOrdFromStd converts a standard Go map to an ordered Map. The resulting ordered Map 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 Map from an existing Go map.

Parameters:

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

Returns:

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

Example usage:

mapOrd := g.MapOrdFromStd[string, int](goMap)

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

func NewMapOrd

func NewMapOrd[K comparable, V any](size ...int) *MapOrd[K, V]

NewMapOrd creates a new ordered Map with the specified size (if provided). An ordered Map is an Map 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 Map. If not provided, a default size will be used.

Returns:

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

Example usage:

mapOrd := g.NewMapOrd[string, int](10)

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

func (*MapOrd[K, V]) Clear

func (mo *MapOrd[K, V]) Clear() *MapOrd[K, V]

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

func (*MapOrd[K, V]) Clone

func (mo *MapOrd[K, V]) Clone() *MapOrd[K, V]

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

func (*MapOrd[K, V]) Contains

func (mo *MapOrd[K, V]) Contains(key K) bool

Contains checks if the ordered Map contains the specified key.

func (*MapOrd[K, V]) Copy

func (mo *MapOrd[K, V]) Copy(src *MapOrd[K, V]) *MapOrd[K, V]

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

func (*MapOrd[K, V]) Delete

func (mo *MapOrd[K, V]) Delete(keys ...K) *MapOrd[K, V]

Delete removes the specified keys from the ordered Map.

func (*MapOrd[K, V]) Empty

func (mo *MapOrd[K, V]) Empty() bool

Empty checks if the ordered Map is empty.

func (*MapOrd[K, V]) Eq

func (mo *MapOrd[K, V]) Eq(other *MapOrd[K, V]) bool

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

func (*MapOrd[K, V]) Filter

func (mo *MapOrd[K, V]) Filter(fn func(K, V) bool) *MapOrd[K, V]

Filter filters the ordered Map based on a provided predicate function, returning a new ordered Map 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 Map 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:

- *MapOrd[K, V]: A pointer to a new ordered Map 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 Map to include only the key-value pairs where the value is greater than 10.

func (*MapOrd[K, V]) ForEach

func (mo *MapOrd[K, V]) ForEach(fn func(K, V))

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

Parameters:

- fn func(K, V): The function to execute for each key-value pair in the ordered Map. 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 Map.

func (*MapOrd[K, V]) Get

func (mo *MapOrd[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 Map. This function is useful when you want to access the value associated with a key in the ordered Map, and also check if the key exists in the map.

Parameters:

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

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 Map.

Example usage:

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

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

func (*MapOrd[K, V]) GetOrDefault

func (mo *MapOrd[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 Map, 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 Map.

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

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 := mo.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 (*MapOrd[K, V]) GetOrSet

func (mo *MapOrd[K, V]) GetOrSet(key K, defaultValue V) V

GetOrSet returns the value for a key. If the key does not exist, it returns the default value instead and also sets the default value for the key in the ordered Map. This function is useful when you want to access the value associated with a key in the ordered Map, and if the key does not exist, you want to return a specified default value and set that default value for the key.

Parameters:

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

- defaultValue V: The default value to return if the key is not found in the ordered Map. If the key is not found, this default value will also be set for the key in the ordered Map.

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 := mo.GetOrSet("some_key", "default_value")

Retrieves the value associated with the key "some_key" or returns "default_value" if the key is not found, and sets "default_value" as the value for "some_key" in the ordered Map if it's not present.

func (*MapOrd[K, V]) Invert

func (mo *MapOrd[K, V]) Invert() *MapOrd[any, K]

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

func (*MapOrd[K, V]) Keys

func (mo *MapOrd[K, V]) Keys() Slice[K]

Keys returns an Slice containing all the keys in the ordered Map.

func (*MapOrd[K, V]) Len

func (mo *MapOrd[K, V]) Len() int

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

func (*MapOrd[K, V]) Map

func (mo *MapOrd[K, V]) Map(fn func(K, V) (K, V)) *MapOrd[K, V]

Map applies a provided function to all key-value pairs in the ordered Map and returns a new ordered Map 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 Map 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:

- *MapOrd[K, V]: A pointer to a new ordered Map 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 Map.

func (*MapOrd[K, V]) Ne

func (mo *MapOrd[K, V]) Ne(other *MapOrd[K, V]) bool

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

func (*MapOrd[K, V]) NotEmpty

func (mo *MapOrd[K, V]) NotEmpty() bool

NotEmpty checks if the ordered Map is not empty.

func (*MapOrd[K, V]) Print

func (mo *MapOrd[K, V]) Print() *MapOrd[K, V]

Print prints the key-value pairs of the MapOrd to the standard output (console) and returns the MapOrd pointer unchanged.

func (*MapOrd[K, V]) Set

func (mo *MapOrd[K, V]) Set(key K, value V) *MapOrd[K, V]

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

func (*MapOrd[K, V]) SortBy

func (mo *MapOrd[K, V]) SortBy(f func(i, j int) bool) *MapOrd[K, V]

SortBy sorts the ordered Map 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 Map based on a custom comparison logic.

Parameters:

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

Returns:

- *MapOrd[K, V]: A pointer to the same ordered Map, 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 (*MapOrd[K, V]) String

func (mo *MapOrd[K, V]) String() string

String returns a string representation of the ordered Map.

func (*MapOrd[K, V]) ToMap

func (mo *MapOrd[K, V]) ToMap() Map[K, V]

ToMap converts the ordered Map to a standard Map.

func (*MapOrd[K, V]) Values

func (mo *MapOrd[K, V]) Values() Slice[V]

Values returns an Slice containing all the values in the ordered Map.

type Option

type Option[T any] struct {
	// contains filtered or unexported fields
}

Option is a generic struct for representing an optional value.

func None

func None[T any]() Option[T]

None creates an Option containing a nil value.

func Some

func Some[T any](value T) Option[T]

Some creates an Option containing a non-nil value.

func (Option[T]) Expect

func (o Option[T]) Expect(msg string) T

Expect returns the value held in the Option. If the Option contains a nil value, it panics with the provided message.

func (Option[T]) IsNone

func (o Option[T]) IsNone() bool

IsNone returns true if the Option contains a nil value.

func (Option[T]) IsSome

func (o Option[T]) IsSome() bool

IsSome returns true if the Option contains a non-nil value.

func (Option[T]) Some

func (o Option[T]) Some() T

Some returns the value held in the Option.

func (Option[T]) Unwrap added in v1.1.4

func (o Option[T]) Unwrap() T

Unwrap returns the value held in the Option. If the Option contains a nil value, it panics.

func (Option[T]) UnwrapOr added in v1.1.4

func (o Option[T]) UnwrapOr(value T) T

UnwrapOr returns the value held in the Option. If the Option contains a nil value, it returns the provided default value.

func (Option[T]) UnwrapOrDefault added in v1.1.4

func (o Option[T]) UnwrapOrDefault() T

UnwrapOrDefault returns the value held in the Option. If the Option contains a value, it returns the value. If the Option is None, it returns the default value for type T.

type Result

type Result[T any] struct {
	// contains filtered or unexported fields
}

Result is a generic struct for representing a result value along with an error.

func Err

func Err[T any](err error) Result[T]

Err returns a new Result[T] containing the given error.

func Ok

func Ok[T any](value T) Result[T]

Ok returns a new Result[T] containing the given value.

func ToResult

func ToResult[T any](value T, err error) Result[T]

ToResult returns a new Result[T] based on the provided value and error. If err is not nil, it returns an Result containing the error. Otherwise, it returns an Result containing the value.

func (Result[T]) Err

func (r Result[T]) Err() error

Err returns the error held in the Result.

func (Result[T]) Expect

func (r Result[T]) Expect(msg string) T

Expect returns the value held in the Result. If the Result contains an error, it panics with the provided message.

func (Result[T]) IsErr

func (r Result[T]) IsErr() bool

IsErr returns true if the Result contains an error.

func (Result[T]) IsOk

func (r Result[T]) IsOk() bool

IsOk returns true if the Result contains a value (no error).

func (Result[T]) Ok

func (r Result[T]) Ok() T

Ok returns the value held in the Result.

func (Result[T]) Result

func (r Result[T]) Result() (T, error)

Result returns the value held in the Result and its error.

func (Result[T]) Unwrap added in v1.1.4

func (r Result[T]) Unwrap() T

Unwrap returns the value held in the Result. If the Result contains an error, it panics.

func (Result[T]) UnwrapOr added in v1.1.4

func (r Result[T]) UnwrapOr(value T) T

UnwrapOr returns the value held in the Result. If the Result contains an error, it returns the provided default value.

func (Result[T]) UnwrapOrDefault added in v1.1.4

func (r Result[T]) UnwrapOrDefault() T

UnwrapOrDefault returns the value held in the Result. If the Result contains an error, it returns the default value for type T. Otherwise, it returns the value held in the Result.

type Set

type Set[T comparable] map[T]struct{}

Set is a generic alias for a set implemented using a map.

func NewSet

func NewSet[T comparable](size ...int) Set[T]

NewSet creates a new Set of the specified size or an empty Set if no size is provided.

func SetMap added in v1.0.4

func SetMap[T, E comparable](s Set[T], fn func(T) E) Set[E]

SetMap applies the given function to each element of a Set and returns a new Set containing the transformed values.

Parameters: - s: The input Set. - fn: The function to apply to each element of the input Set.

Returns: A new Set containing the results of applying the function to each element of the input Set.

func SetOf

func SetOf[T comparable](values ...T) Set[T]

SetOf creates a new generic set containing the provided elements.

func (Set[T]) Add

func (s Set[T]) Add(values ...T) Set[T]

Add adds the provided elements to the set and returns the modified set.

func (Set[T]) Clear

func (s Set[T]) Clear() Set[T]

Clear removes all values from the Set.

func (Set[T]) Clone

func (s Set[T]) Clone() Set[T]

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

func (Set[T]) Contains

func (s Set[T]) Contains(v T) bool

Contains checks if the Set contains the specified value.

func (Set[T]) ContainsAll

func (s Set[T]) ContainsAll(other Set[T]) bool

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

func (Set[T]) ContainsAny

func (s Set[T]) ContainsAny(other Set[T]) bool

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

func (Set[T]) Difference

func (s Set[T]) Difference(other Set[T]) Set[T]

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

Parameters:

- other Set[T]: The other set to calculate the difference with.

Returns:

- Set[T]: A new Set containing the difference between the two sets.

Example usage:

s1 := g.SetOf(1, 2, 3, 4, 5)
s2 := g.SetOf(4, 5, 6, 7, 8)
diff := s1.Difference(s2)

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

func (Set[T]) Empty

func (s Set[T]) Empty() bool

Empty checks if the Set is empty.

func (Set[T]) Eq

func (s Set[T]) Eq(other Set[T]) bool

Eq checks if two Sets are equal.

func (Set[T]) Filter

func (s Set[T]) Filter(fn func(T) bool) Set[T]

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

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

Parameters:

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

Returns:

- Set[T]: A new set containing the elements that satisfy the given condition.

Example usage:

s := g.SetOf(1, 2, 3, 4, 5)
even := s.Filter(func(val int) bool {
    return val%2 == 0
})
fmt.Println(even)

Output: [2 4].

func (Set[T]) ForEach

func (s Set[T]) ForEach(fn func(T))

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

Parameters:

- fn func(T): A function that takes a value as input parameter and performs an operation.

Example usage:

originalSet.ForEach(func(value T) {
	fmt.Printf("Value: %v\n", value)
})

func (Set[T]) Intersection

func (s Set[T]) Intersection(other Set[T]) Set[T]

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

Parameters:

- other Set[T]: The other set to calculate the intersection with.

Returns:

- Set[T]: A new Set containing the intersection of the two sets.

Example usage:

s1 := g.SetOf(1, 2, 3, 4, 5)
s2 := g.SetOf(4, 5, 6, 7, 8)
intersection := s1.Intersection(s2)

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

func (Set[T]) Len

func (s Set[T]) Len() int

Len returns the number of values in the Set.

func (Set[T]) Map

func (s Set[T]) Map(fn func(T) T) Set[T]

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

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

Parameters:

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

Returns:

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

Example usage:

s := g.SetOf(1, 2, 3)
doubled := s.Map(func(val int) int {
    return val * 2
})
fmt.Println(doubled)

Output: [2 4 6].

func (Set[T]) Ne

func (s Set[T]) Ne(other Set[T]) bool

Ne checks if two Sets are not equal.

func (Set[T]) Print

func (s Set[T]) Print() Set[T]

Print prints the elements of the Set to the standard output (console) and returns the Set unchanged.

func (Set[T]) Remove

func (s Set[T]) Remove(values ...T) Set[T]

Remove removes the specified values from the Set.

func (Set[T]) String

func (s Set[T]) String() string

String returns a string representation of the Set.

func (Set[T]) Subset

func (s Set[T]) Subset(other Set[T]) bool

Subset checks if the current set 's' is a subset of the provided 'other' set. A set 's' is a subset of 'other' if all elements of 's' are also elements of 'other'.

Parameters:

- other Set[T]: The other set to compare with.

Returns:

- bool: true if 's' is a subset of 'other', false otherwise.

Example usage:

s1 := g.SetOf(1, 2, 3)
s2 := g.SetOf(1, 2, 3, 4, 5)
isSubset := s1.Subset(s2) // Returns true

func (Set[T]) Superset

func (s Set[T]) Superset(other Set[T]) bool

Superset checks if the current set 's' is a superset of the provided 'other' set. A set 's' is a superset of 'other' if all elements of 'other' are also elements of 's'.

Parameters:

- other Set[T]: The other set to compare with.

Returns:

- bool: true if 's' is a superset of 'other', false otherwise.

Example usage:

s1 := g.SetOf(1, 2, 3, 4, 5)
s2 := g.SetOf(1, 2, 3)
isSuperset := s1.Superset(s2) // Returns true

func (Set[T]) SymmetricDifference

func (s Set[T]) SymmetricDifference(other Set[T]) Set[T]

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

Parameters:

- other Set[T]: The other set to calculate the symmetric difference with.

Returns:

- Set[T]: A new Set containing the symmetric difference between the two sets.

Example usage:

s1 := g.SetOf(1, 2, 3, 4, 5)
s2 := g.SetOf(4, 5, 6, 7, 8)
symDiff := s1.SymmetricDifference(s2)

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

func (Set[T]) ToSlice

func (s Set[T]) ToSlice() Slice[T]

ToSlice returns a new Slice with the same elements as the Set[T].

func (Set[T]) Union

func (s Set[T]) Union(other Set[T]) Set[T]

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

Parameters:

- other Set[T]: The other set to create the union with.

Returns:

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

Example usage:

s1 := g.SetOf(1, 2, 3)
s2 := g.SetOf(3, 4, 5)
union := s1.Union(s2)

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

type Slice

type Slice[T any] []T

Slice is a generic alias for a slice.

func NewSlice

func NewSlice[T any](size ...int) Slice[T]

NewSlice creates a new Slice 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 Slice with a length and capacity of 0 is returned. If one value is provided, it sets both the length and capacity of the Slice. 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 Slice

Returns:

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

Example usage:

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

func SliceMap added in v1.0.4

func SliceMap[T, E any](sl Slice[T], fn func(T) E) Slice[E]

SliceMap applies the given function to each element of a Slice and returns a new Slice containing the transformed values.

Parameters: - sl: The input Slice. - fn: The function to apply to each element of the input Slice.

Returns: A new Slice containing the results of applying the function to each element of the input Slice.

func SliceOf

func SliceOf[T any](slice ...T) Slice[T]

SliceOf creates a new generic slice containing the provided elements.

func (Slice[T]) AddUnique

func (sl Slice[T]) AddUnique(elems ...T) Slice[T]

AddUnique 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. The resulting slice is returned, containing the unique elements from both the original slice and the provided elements.

Parameters:

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

Returns:

- Slice[T]: A new slice containing the unique elements from both the original slice and the provided elements.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5}
slice = slice.AddUnique(3, 4, 5, 6, 7)
fmt.Println(slice)

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

func (*Slice[T]) AddUniqueInPlace

func (sl *Slice[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 := g.Slice[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 (Slice[T]) All

func (sl Slice[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 Slice 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 Slice satisfy the condition, false otherwise.

Example usage:

slice := g.Slice[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 (Slice[T]) Any

func (sl Slice[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 Slice 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 Slice satisfies the condition, false otherwise.

Example usage:

slice := g.Slice[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 (Slice[T]) Append

func (sl Slice[T]) Append(elems ...T) Slice[T]

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

func (*Slice[T]) AppendInPlace

func (sl *Slice[T]) AppendInPlace(elems ...T)

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

func (Slice[T]) Batched added in v1.0.8

func (sl Slice[T]) Batched(size int) []Slice[T]

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

Parameters:

- size int: The size of each batch.

Returns:

- []Slice[T]: A slice of Slice[T] containing the batches of the original Slice.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5, 6}
batches := slice.Batched(2)

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

func (Slice[T]) Cap

func (sl Slice[T]) Cap() int

Cap returns the capacity of the Slice.

func (Slice[T]) Clear

func (sl Slice[T]) Clear() Slice[T]

Clear removes all elements from the Slice and sets its length to 0.

func (Slice[T]) Clip

func (sl Slice[T]) Clip() Slice[T]

Clip removes unused capacity from the slice.

func (Slice[T]) Clone

func (sl Slice[T]) Clone() Slice[T]

Clone returns a copy of the slice.

func (Slice[T]) Contains

func (sl Slice[T]) Contains(val T) bool

Contains returns true if the slice contains the provided value.

func (Slice[T]) ContainsAll

func (sl Slice[T]) ContainsAll(other Slice[T]) bool

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

func (Slice[T]) ContainsAny

func (sl Slice[T]) ContainsAny(other Slice[T]) bool

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

func (Slice[T]) Count

func (sl Slice[T]) Count(elem T) int

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

func (Slice[T]) Counter

func (sl Slice[T]) Counter() *MapOrd[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 Slice.

Returns:

- *MapOrd[any, int]: An ordered Map with keys representing the unique elements in the Slice and values representing the counts of those elements.

Example usage:

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

func (Slice[T]) Cut

func (sl Slice[T]) Cut(start, end int) Slice[T]

Cut removes a range of elements from the Slice and returns a new Slice. It creates two slices: one from the beginning of the original slice up to the specified start index (exclusive), and another from the specified end index (inclusive) to the end of the original slice. These two slices are then concatenated to form the resulting Slice.

Parameters:

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

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

Note:

The function also supports negative indices. Negative indices are counted
from the end of the slice. For example, -1 means the last element, -2
means the second-to-last element, and so on.

Returns:

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

Example:

slice := g.Slice[int]{1, 2, 3, 4, 5}
newSlice := slice.Cut(1, 3)
// newSlice is [1 4 5]

func (Slice[T]) Delete

func (sl Slice[T]) Delete(i int) Slice[T]

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

func (*Slice[T]) DeleteInPlace

func (sl *Slice[T]) DeleteInPlace(i int)

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

func (Slice[T]) Empty

func (sl Slice[T]) Empty() bool

Empty returns true if the slice is empty.

func (Slice[T]) Enumerate

func (sl Slice[T]) Enumerate() Map[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 Map where the keys are the indices of the elements in an Slice, and the values are the corresponding elements.

Returns:

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

Example usage:

slice := g.Slice[int]{10, 20, 30}
indexedMap := slice.Enumerate()
// The indexedMap Map 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 (Slice[T]) Eq

func (sl Slice[T]) Eq(other Slice[T]) bool

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

func (Slice[T]) Fill

func (sl Slice[T]) Fill(val T) Slice[T]

Fill fills the slice with the specified value. This function is useful when you want to create an Slice 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 Slice with.

Returns:

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

Example usage:

slice := g.Slice[int]{0, 0, 0}
slice.Fill(5)

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

func (Slice[T]) Filter

func (sl Slice[T]) Filter(fn func(T) bool) Slice[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:

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

Example usage:

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

Output: [2 4].

func (*Slice[T]) FilterInPlace

func (sl *Slice[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 := g.Slice[int]{1, 2, 3, 4, 5}
slice.FilterInPlace(func(val int) bool {
    return val%2 == 0
})
fmt.Println(slice)

Output: [2 4].

func (Slice[T]) FilterParallel

func (sl Slice[T]) FilterParallel(fn func(T) bool) Slice[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:

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

Example usage:

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

Output: {2 4}.

func (Slice[T]) FilterZeroValues

func (sl Slice[T]) FilterZeroValues() Slice[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:

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

Example usage:

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

Output: [1 2 4].

func (*Slice[T]) FilterZeroValuesInPlace

func (sl *Slice[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 := g.Slice[int]{1, 2, 0, 4, 0}
slice.FilterZeroValuesInPlace()
fmt.Println(slice)

Output: [1 2 4].

func (Slice[T]) Flatten

func (sl Slice[T]) Flatten() Slice[any]

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

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

Returns:

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

Example usage:

nested := g.Slice[any]{1, 2, g.Slice[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 (Slice[T]) ForEach

func (sl Slice[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 := g.Slice[int]{1, 2, 3}
slice.ForEach(func(val int) {
    fmt.Println(val * 2)
})
// Output:
// 2
// 4
// 6

func (Slice[T]) Get

func (sl Slice[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 (Slice[T]) Grow

func (sl Slice[T]) Grow(n int) Slice[T]

Grow increases the slice's capacity, if necessary, to guarantee space for another n elements. After Grow(n), at least n elements can be appended to the slice without another allocation. If n is negative or too large to allocate the memory, Grow panics.

func (Slice[T]) Index

func (sl Slice[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 (Slice[T]) Insert

func (sl Slice[T]) Insert(i int, values ...T) Slice[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:

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

Example usage:

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

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

func (*Slice[T]) InsertInPlace

func (sl *Slice[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 := g.Slice[string]{"a", "b", "c", "d"}
slice.InsertInPlace(2, "e", "f")

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

func (Slice[T]) Join

func (sl Slice[T]) Join(sep ...T) String

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

func (Slice[T]) Last

func (sl Slice[T]) Last() T

Last returns the last element of the slice.

func (Slice[T]) LastIndex

func (sl Slice[T]) LastIndex() int

LastIndex returns the last index of the slice.

func (Slice[T]) Len

func (sl Slice[T]) Len() int

Len returns the length of the slice.

func (Slice[T]) Map

func (sl Slice[T]) Map(fn func(T) T) Slice[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:

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

Example usage:

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

Output: [2 4 6].

func (*Slice[T]) MapInPlace

func (sl *Slice[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 := g.Slice[int]{1, 2, 3}
slice.MapInPlace(func(val int) int {
    return val * 2
})
fmt.Println(slice)

Output: [2 4 6].

func (Slice[T]) MapParallel

func (sl Slice[T]) MapParallel(fn func(T) T) Slice[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:

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

Example usage:

slice := g.Slice[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 (Slice[T]) Max

func (sl Slice[T]) Max() T

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

func (Slice[T]) Min

func (sl Slice[T]) Min() T

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

func (Slice[T]) Ne

func (sl Slice[T]) Ne(other Slice[T]) bool

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

func (Slice[T]) NotEmpty

func (sl Slice[T]) NotEmpty() bool

NotEmpty returns true if the slice is not empty.

func (Slice[T]) Permutations

func (sl Slice[T]) Permutations() []Slice[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:

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

Example usage:

slice := g.Slice[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 (Slice[T]) Pop

func (sl Slice[T]) Pop() (T, Slice[T])

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

func (Slice[T]) Print

func (sl Slice[T]) Print() Slice[T]

Print prints the elements of the Slice to the standard output (console) and returns the Slice unchanged.

func (Slice[T]) Random

func (sl Slice[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 := g.Slice[int]{1, 2, 3, 4, 5}
randomElement := slice.Random()
fmt.Println(randomElement)

Output: <any random element from the slice>.

func (Slice[T]) RandomRange added in v1.1.1

func (sl Slice[T]) RandomRange(from, to int) Slice[T]

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

Parameters:

- from int: The starting index of the subrange (inclusive). - to int: The ending index of the subrange (exclusive).

Returns:

- Slice[T]: A new Slice containing the random sample of elements from the specified subrange.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5, 6, 7, 8, 9}
subrange := slice.RandomRange(2, 7)

The resulting subrange will contain a random sample of elements from index 2 (inclusive) to index 7 (exclusive) of the original slice.

func (Slice[T]) RandomSample

func (sl Slice[T]) RandomSample(sequence int) Slice[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 unique elements to include in the random sample.

Returns:

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

Example usage:

slice := g.Slice[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 (Slice[T]) Range

func (sl Slice[T]) Range(start int, end ...int) Slice[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 represents the position from the end of the slice. If the start index is negative, it represents the position from the end of the slice counted from the start index. If the start index is greater than or equal to 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, optional): The end index of the range. If not provided, the end index will be the length of the slice.

Returns:

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

Example usage:

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

Output: [2 3 4].

func (Slice[T]) Reduce

func (sl Slice[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 := g.Slice[int]{1, 2, 3, 4, 5}
sum := slice.Reduce(func(acc, val int) int {
    return acc + val
}, 0)
fmt.Println(sum)

Output: 15.

func (Slice[T]) ReduceParallel

func (sl Slice[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 := g.Slice[int]{1, 2, 3, 4, 5}
sum := slice.ReduceParallel(func(acc, val int) int {
    return acc + val
}, 0)
fmt.Println(sum)

Output: 15.

func (Slice[T]) Replace

func (sl Slice[T]) Replace(i, j int, values ...T) Slice[T]

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

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:

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

Example usage:

slice := g.Slice[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 (*Slice[T]) ReplaceInPlace

func (sl *Slice[T]) ReplaceInPlace(i, j int, values ...T)

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

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 := g.Slice[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 (Slice[T]) Reverse

func (sl Slice[T]) Reverse() Slice[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:

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

Example usage:

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

Output: [5 4 3 2 1].

func (Slice[T]) Set

func (sl Slice[T]) Set(i int, val T) Slice[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:

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

Example usage:

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

Output: [1 2 99 4 5].

func (Slice[T]) Shuffle

func (sl Slice[T]) Shuffle() Slice[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:

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

Example usage:

slice := g.Slice[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 (Slice[T]) SortBy

func (sl Slice[T]) SortBy(f func(i, j int) bool) Slice[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:

- Slice[T]: The sorted Slice.

Example usage:

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

func (Slice[T]) Std

func (sl Slice[T]) Std() []T

Std returns a new slice with the same elements as the Slice[T].

func (Slice[T]) String

func (sl Slice[T]) String() string

String returns a string representation of the slice.

func (Slice[T]) Swap

func (sl Slice[T]) Swap(i, j int) Slice[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:

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

Example usage:

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

Output: [1 4 3 2 5].

func (Slice[T]) ToMapHashed

func (sl Slice[T]) ToMapHashed() Map[String, T]

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

func (Slice[T]) ToStringSlice

func (sl Slice[T]) ToStringSlice() []string

ToStringSlice converts the slice into a slice of strings.

func (Slice[T]) Unique

func (sl Slice[T]) Unique() Slice[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:

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

Example usage:

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

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

func (Slice[T]) Zip

func (sl Slice[T]) Zip(ss ...Slice[T]) []Slice[T]

Zip zips the elements of the given slices with the current slice into a new slice of Slice[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 Slice[T] elements is determined by the shortest input slice.

Params:

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

Returns:

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

Example usage:

slice1 := g.Slice[int]{1, 2, 3}
slice2 := g.Slice[int]{4, 5, 6}
slice3 := g.Slice[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 String

type String string

String is an alias for the string type.

func NewString

func NewString(str string) String

NewString creates a new String from the provided string.

func (String) Add

func (s String) Add(str String) String

Add appends the specified String to the current String.

func (String) AddPrefix

func (s String) AddPrefix(str String) String

AddPrefix prepends the specified String to the current String.

func (String) Center

func (s String) Center(length int, pad String) String

Center justifies the String by adding padding on both sides, up to the specified length. If the length of the String is already greater than or equal to the specified length, or the pad is empty, the original String is returned.

The padding String is repeated as necessary to evenly distribute the remaining length on both sides. The padding is added to the left and right of the String.

Parameters:

  • length: The desired length of the resulting justified String.
  • pad: The String used as padding.

Example usage:

s := g.String("Hello")
result := s.Center(10, "...")
// result: "..Hello..."

func (String) Chunks

func (s String) Chunks(size int) Option[Slice[String]]

Chunks splits the String into chunks of the specified size.

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

Parameters:

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

Returns:

- Slice[String]: A slice of String chunks of the specified size.

Example usage:

text := g.String("Hello, World!")
chunks := text.Chunks(4).Some()

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

func (String) Comp added in v1.1.5

func (s String) Comp() comp

Comp returns a comp struct wrapping the given String.

func (String) Compare

func (s String) Compare(str String) Int

Compare compares two Strings and returns an Int indicating their relative order. The result will be 0 if s==str, -1 if s < str, and +1 if s > str.

func (String) Contains

func (s String) Contains(substr String) bool

Contains checks if the String contains the specified substring.

func (String) ContainsAll

func (s String) ContainsAll(substrs ...String) bool

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

func (String) ContainsAny

func (s String) ContainsAny(substrs ...String) bool

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

func (String) ContainsAnyChars

func (s String) ContainsAnyChars(chars String) bool

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

func (String) ContainsRegexp

func (s String) ContainsRegexp(pattern String) Result[bool]

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

func (String) ContainsRegexpAll

func (s String) ContainsRegexpAll(patterns ...String) Result[bool]

ContainsRegexpAll checks if the String contains a match for all of the specified regular expression patterns.

func (String) ContainsRegexpAny

func (s String) ContainsRegexpAny(patterns ...String) Result[bool]

ContainsRegexpAny checks if the String contains a match for any of the specified regular expression patterns.

func (String) ContainsRune

func (s String) ContainsRune(r rune) bool

ContainsRune checks if the String contains the specified rune.

func (String) Count

func (s String) Count(substr String) int

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

func (String) Cut

func (s String) Cut(start, end String, rmtags ...bool) (String, String)

Cut returns two String values. The first String contains the remainder of the original String after the cut. The second String contains the text between the first occurrences of the 'start' and 'end' strings, with tags removed if specified.

The function searches for the 'start' and 'end' strings within the String. If both are found, it returns the first String containing the remainder of the original String after the cut, followed by the second String containing the text between the first occurrences of 'start' and 'end' with tags removed if specified.

If either 'start' or 'end' is empty or not found in the String, it returns the original String as the second String, and an empty String as the first.

Parameters:

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

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

  • rmtags (bool, optional): An optional boolean parameter indicating whether to remove 'start' and 'end' tags from the cut text. Defaults to false.

Returns:

  • String: The first String containing the remainder of the original String after the cut, with tags removed if specified, or an empty String if 'start' or 'end' is empty or not found.

  • String: The second String containing the text between the first occurrences of 'start' and 'end', or the original String if 'start' or 'end' is empty or not found.

Example usage:

s := g.String("Hello, [world]! How are you?")
remainder, cut := s.Cut("[", "]")
// remainder: "Hello, ! How are you?"
// cut: "world"

func (String) Dec

func (s String) Dec() dec

Dec returns a dec struct wrapping the given String.

func (String) Decomp added in v1.1.5

func (s String) Decomp() decomp

Decomp returns a decomp struct wrapping the given String.

func (String) Empty

func (s String) Empty() bool

Empty checks if the String is empty.

func (String) Enc

func (s String) Enc() enc

Enc returns an enc struct wrapping the given String.

func (String) EndsWith

func (s String) EndsWith(suffixes ...String) bool

EndsWith checks if the String ends with any of the provided suffixes. The method accepts a variable number of arguments, allowing for checking against multiple suffixes at once. It iterates over the provided suffixes and uses the HasSuffix function from the strings package to check if the String ends with each suffix. The function returns true if the String ends with any of the suffixes, and false otherwise.

Example usage:

s := g.String("example.com")
if s.EndsWith(".com", ".net") {
   // do something
}

func (String) Eq

func (s String) Eq(str String) bool

Eq checks if two Strings are equal.

func (String) EqFold

func (s String) EqFold(str String) bool

EqFold compares two String strings case-insensitively.

func (String) Fields

func (s String) Fields() Slice[String]

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

func (String) FindAllRegexp

func (s String) FindAllRegexp(pattern *regexp.Regexp) Option[Slice[String]]

FindAllRegexp searches the String for all occurrences of the regular expression pattern and returns an Option[Slice[String]] containing a slice of matched substrings. If no matches are found, the Option[Slice[String]] will be None.

func (String) FindAllRegexpN

func (s String) FindAllRegexpN(pattern *regexp.Regexp, n Int) Option[Slice[String]]

FindAllRegexpN searches the String for up to n occurrences of the regular expression pattern and returns an Option[Slice[String]] containing a slice of matched substrings. If no matches are found, the Option[Slice[String]] will be None. If n is negative, all occurrences will be returned.

func (String) FindAllSubmatchRegexp

func (s String) FindAllSubmatchRegexp(pattern *regexp.Regexp) Option[Slice[Slice[String]]]

FindAllSubmatchRegexp searches the String for all occurrences of the regular expression pattern and returns an Option[Slice[Slice[String]]] containing the matched substrings and submatches. The Option[Slice[Slice[String]]] will contain an Slice[String] for each match, where each Slice[String] will contain the full match at index 0, followed by any captured submatches. If no match is found, the Option[Slice[Slice[String]]] will be None. This method is equivalent to calling SubmatchAllRegexpN with n = -1, which means it finds all occurrences.

func (String) FindAllSubmatchRegexpN

func (s String) FindAllSubmatchRegexpN(pattern *regexp.Regexp, n Int) Option[Slice[Slice[String]]]

FindAllSubmatchRegexpN searches the String for occurrences of the regular expression pattern and returns an Option[Slice[Slice[String]]] containing the matched substrings and submatches. The Option[Slice[Slice[String]]] will contain an Slice[String] for each match, where each Slice[String] will contain the full match at index 0, followed by any captured submatches. If no match is found, the Option[Slice[Slice[String]]] will be None. The 'n' parameter specifies the maximum number of matches to find. If n is negative, it finds all occurrences.

func (String) FindRegexp

func (s String) FindRegexp(pattern *regexp.Regexp) Option[String]

FindRegexp searches the String for the first occurrence of the regulare xpression pattern and returns an Option[String] containing the matched substring. If no match is found, it returns None.

func (String) FindSubmatchRegexp

func (s String) FindSubmatchRegexp(pattern *regexp.Regexp) Option[Slice[String]]

FindSubmatchRegexp searches the String for the first occurrence of the regular expression pattern and returns an Option[Slice[String]] containing the matched substrings and submatches. The Option will contain an Slice[String] with the full match at index 0, followed by any captured submatches. If no match is found, it returns None.

func (String) Format

func (s String) Format(format String) String

Format applies a specified format to the String object.

func (String) Gt

func (s String) Gt(str String) bool

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

func (String) Hash

func (s String) Hash() shash

Hash returns a shash struct wrapping the given String.

func (String) Index

func (s String) Index(substr String) int

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

func (String) IndexRegexp

func (s String) IndexRegexp(pattern *regexp.Regexp) Option[Slice[Int]]

IndexRegexp searches for the first occurrence of the regular expression pattern in the String. If a match is found, it returns an Option containing an Slice with the start and end indices of the match. If no match is found, it returns None.

func (String) IndexRune

func (s String) IndexRune(r rune) int

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

func (String) IsASCII

func (s String) IsASCII() bool

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

func (String) IsDigit

func (s String) IsDigit() bool

IsDigit checks if all characters in the String are digits.

func (String) LastIndex

func (s String) LastIndex(substr String) int

LastIndex returns the index of the last instance of the specified substring in the String, or -1 if substr is not present in s.

func (String) LeftJustify

func (s String) LeftJustify(length int, pad String) String

LeftJustify justifies the String to the left by adding padding to the right, up to the specified length. If the length of the String is already greater than or equal to the specified length, or the pad is empty, the original String is returned.

The padding String is repeated as necessary to fill the remaining length. The padding is added to the right of the String.

Parameters:

  • length: The desired length of the resulting justified String.
  • pad: The String used as padding.

Example usage:

s := g.String("Hello")
result := s.LeftJustify(10, "...")
// result: "Hello....."

func (String) Len

func (s String) Len() int

Len returns the length of the String.

func (String) LenRunes

func (s String) LenRunes() int

LenRunes returns the number of runes in the String.

func (String) Lower added in v1.0.4

func (s String) Lower() String

Lower returns the String in lowercase.

func (String) Lt

func (s String) Lt(str String) bool

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

func (String) Map

func (s String) Map(fn func(rune) rune) String

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

func (String) Max

func (s String) Max(b ...String) String

Max returns the maximum of Strings.

func (String) Min

func (s String) Min(b ...String) String

Min returns the minimum of Strings.

func (String) Ne

func (s String) Ne(str String) bool

Ne checks if two Strings are not equal.

func (String) NormalizeNFC

func (s String) NormalizeNFC() String

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

func (String) NotEmpty

func (s String) NotEmpty() bool

NotEmpty checks if the String is not empty.

func (String) Print

func (s String) Print() String

Print prints the content of the String to the standard output (console) and returns the String unchanged.

func (String) Random

func (String) Random(count int) String

Random generates a random String 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 String.

Parameters:

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

Returns:

- String: A random String with the specified length.

Example usage:

randomString := g.String.Random(10)

randomString contains a random String with 10 characters.

func (String) Reader

func (s String) Reader() *strings.Reader

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

func (String) Repeat

func (s String) Repeat(count int) String

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

func (String) Replace

func (s String) Replace(oldS, newS String, n int) String

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

func (String) ReplaceAll

func (s String) ReplaceAll(oldS, newS String) String

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

func (String) ReplaceMulti

func (s String) ReplaceMulti(oldnew ...String) String

ReplaceMulti creates a custom replacer to perform multiple string replacements.

Parameters:

- oldnew ...String: Pairs of strings to be replaced. Specify as many pairs as needed.

Returns:

- String: A new string with replacements applied using the custom replacer.

Example usage:

original := g.String("Hello, world! This is a test.")
replaced := original.ReplaceMulti(
    "Hello", "Greetings",
    "world", "universe",
    "test", "example",
)
// replaced contains "Greetings, universe! This is an example."

func (String) ReplaceNth

func (s String) ReplaceNth(oldS, newS String, n int) String

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

Returns:

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

Example usage:

s := g.String("The quick brown dog jumped over the lazy dog.")
result := s.ReplaceNth("dog", "fox", 2)
fmt.Println(result)

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

func (String) ReplaceRegexp

func (s String) ReplaceRegexp(pattern *regexp.Regexp, newS String) String

ReplaceRegexp replaces all occurrences of the regular expression matches in the String with the provided newS (as a String) and returns the resulting String after the replacement.

func (String) Reverse

func (s String) Reverse() String

Reverse reverses the String.

func (String) RightJustify

func (s String) RightJustify(length int, pad String) String

RightJustify justifies the String to the right by adding padding to the left, up to the specified length. If the length of the String is already greater than or equal to the specified length, or the pad is empty, the original String is returned.

The padding String is repeated as necessary to fill the remaining length. The padding is added to the left of the String.

Parameters:

  • length: The desired length of the resulting justified String.
  • pad: The String used as padding.

Example usage:

s := g.String("Hello")
result := s.RightJustify(10, "...")
// result: ".....Hello"

func (String) Similarity

func (s String) Similarity(str String) Float

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

The function compares two Strings 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 Strings.

Parameters:

- str (String): The String to compare with s.

Returns:

- Float: The similarity percentage between the two Strings as a value between 0 and 100.

Example usage:

s1 := g.String("kitten")
s2 := g.String("sitting")
similarity := s1.Similarity(s2) // 57.14285714285714

func (String) Split

func (s String) Split(sep ...String) Slice[String]

Split splits the String by the specified separator.

func (String) SplitLines added in v1.1.3

func (s String) SplitLines() Slice[String]

SplitLines splits the String by lines.

func (String) SplitN

func (s String) SplitN(sep String, n Int) Slice[String]

SplitN splits the String into substrings using the provided separator and returns an Slice[String] of the results. The n parameter controls the number of substrings to return: - If n is negative, there is no limit on the number of substrings returned. - If n is zero, an empty Slice[String] is returned. - If n is positive, at most n substrings are returned.

func (String) SplitRegexp

func (s String) SplitRegexp(pattern regexp.Regexp) Slice[String]

SplitRegexp splits the String into substrings using the provided regular expression pattern and returns an Slice[String] of the results. The regular expression pattern is provided as a regexp.Regexp parameter.

func (String) SplitRegexpN

func (s String) SplitRegexpN(pattern regexp.Regexp, n Int) Option[Slice[String]]

SplitRegexpN splits the String into substrings using the provided regular expression pattern and returns an Slice[String] of the results. The regular expression pattern is provided as a regexp.Regexp parameter. The n parameter controls the number of substrings to return: - If n is negative, there is no limit on the number of substrings returned. - If n is zero, an empty Slice[String] is returned. - If n is positive, at most n substrings are returned.

func (String) StartsWith

func (s String) StartsWith(prefixes ...String) bool

StartsWith checks if the String starts with any of the provided prefixes. The method accepts a variable number of arguments, allowing for checking against multiple prefixes at once. It iterates over the provided prefixes and uses the HasPrefix function from the strings package to check if the String starts with each prefix. The function returns true if the String starts with any of the prefixes, and false otherwise.

Example usage:

s := g.String("http://example.com")
if s.StartsWith("http://", "https://") {
   // do something
}

func (String) Std

func (s String) Std() string

Std returns the String as a string.

func (String) Title added in v1.0.4

func (s String) Title() String

Title converts the String to title case.

func (String) ToBytes

func (s String) ToBytes() Bytes

Bytes returns the String as an Bytes.

func (String) ToFloat

func (s String) ToFloat() Result[Float]

ToFloat tries to parse the String as a float64 and returns an Float.

func (String) ToInt

func (s String) ToInt() Result[Int]

ToInt tries to parse the String as an int and returns an Int.

func (String) ToRunes

func (s String) ToRunes() []rune

ToRunes returns the String as a slice of runes.

func (String) Trim

func (s String) Trim(cutset String) String

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

func (String) TrimLeft

func (s String) TrimLeft(cutset String) String

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

func (String) TrimPrefix

func (s String) TrimPrefix(cutset String) String

TrimPrefix trims the specified prefix from the String.

func (String) TrimRight

func (s String) TrimRight(cutset String) String

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

func (String) TrimSpace

func (s String) TrimSpace() String

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

func (String) TrimSuffix

func (s String) TrimSuffix(cutset String) String

TrimSuffix trims the specified suffix from the String.

func (String) Upper added in v1.0.4

func (s String) Upper() String

Upper returns the String in uppercase.

Directories

Path Synopsis
internal
filelock
Package filelock provides a platform-independent API for advisory file locking.
Package filelock provides a platform-independent API for advisory file locking.
pkg
dbg
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.
minmax
Package minmax provides functions for finding the maximum and minimum values.
Package minmax provides functions for finding the maximum and minimum values.
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