Skip to content

duke-git/lancet

main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
April 26, 2023 14:59
April 26, 2023 14:59
April 26, 2023 14:59
May 31, 2023 17:13
May 31, 2023 17:13
April 26, 2023 14:59
April 24, 2023 11:00
December 26, 2022 17:20
April 26, 2023 14:59
April 27, 2023 12:03
May 19, 2023 11:42
April 17, 2023 10:04
November 28, 2021 21:18
May 25, 2023 19:29
May 25, 2023 19:29
November 16, 2022 11:31
April 17, 2023 17:00
April 17, 2023 17:00
July 8, 2022 10:52

README.md


Go version Release GoDoc Go Report Card test codecov License

Lancet is a comprehensive, efficient, and reusable util function library of go. Inspired by the java apache common package and lodash.js.

English | 简体中文

Feature

  • 👏 Comprehensive, efficient and reusable.
  • 💪 500+ go util functions, support string, slice, datetime, net, crypt...
  • 💅 Only depends on two kinds of libraries: go standard library and golang.org/x.
  • 🌍 Unit test for every exported function.

Installation

Note:

  1. For users who use go1.18 and above, it is recommended to install lancet v2.x.x. Cause in v2.x.x all functions was rewriten with generics of go1.18.
go get github.com/duke-git/lancet/v2 // will install latest version of v2.x.x
  1. For users who use version below go1.18, you should install v1.x.x. The latest of v1.x.x is v1.3.8.
go get github.com/duke-git/lancet // below go1.18, install latest version of v1.x.x

Usage

Lancet organizes the code into package structure, and you need to import the corresponding package name when use it. For example, if you use string-related functions,import the strutil package like below:

import "github.com/duke-git/lancet/v2/strutil"

Example

Here takes the string function Reverse (reverse order string) as an example, and the strutil package needs to be imported.

package main

import (
    "fmt"
    "github.com/duke-git/lancet/v2/strutil"
)

func main() {
    s := "hello"
    rs := strutil.Reverse(s)
    fmt.Println(rs) //olleh
}

Documentation

1. Algorithm package implements some basic algorithm. eg. sort, search.

import "github.com/duke-git/lancet/v2/algorithm"

Function list:

  • BubbleSort : sorts slice with bubble sort algorithm, will change the original slice. [doc] [play]
  • CountSort : sorts slice with bubble sort algorithm, don't change original slice. [doc] [play]
  • HeapSort : sorts slice with heap sort algorithm, will change the original slice. [doc] [play]
  • InsertionSort : sorts slice with insertion sort algorithm, will change the original slice. [doc] [play]
  • MergeSort : sorts slice with merge sort algorithm, will change the original slice. [doc] [play]
  • QuickSort : sorts slice with quick sort algorithm, will change the original slice. [doc] [play]
  • SelectionSort : sorts slice with selection sort algorithm, will change the original slice. [doc] [play]
  • ShellSort : sorts slice with shell sort algorithm, will change the original slice. [doc] [play]
  • BinarySearch : returns the index of target within a sorted slice, use binary search (recursive call itself). [doc] [play]
  • BinaryIterativeSearch : returns the index of target within a sorted slice, use binary search (no recursive). [doc] [play]
  • LinearSearch : returns the index of target in slice base on equal function. [doc] [play]
  • LRUCache : implements memory cache with lru algorithm. [doc] [play]

2. Compare package provides a lightweight comparison function on any type.

import "github.com/duke-git/lancet/v2/compare"

Function list:

  • Equal : Checks if two values are equal or not. (check both type and value) [doc] [play]
  • EqualValue : Checks if two values are equal or not. (check value only) [doc] [play]
  • LessThan : Checks if value left less than value right. [doc] [play]
  • GreaterThan : Checks if value left greater than value right. [doc] [play]
  • LessOrEqual : Checks if value left less than or equal than value right. [doc] [play]
  • GreaterOrEqual : Checks if value left less greater or equal than value right. [doc] [play]

3. Concurrency package contain some functions to support concurrent programming. eg, goroutine, channel, async.

import "github.com/duke-git/lancet/v2/concurrency"

Function list:

  • NewChannel : create a Channel pointer instance. [doc] [play]
  • Bridge : link multiply channels into one channel. [doc] [play]
  • FanIn : merge multiple channels into one channel. [doc] [play]
  • Generate : creates a channel, then put values into the channel. [doc] [play]
  • Or : read one or more channels into one channel, will close when any readin channel is closed. [doc] [play]
  • OrDone : read a channel into another channel, will close until cancel context. [doc] [play]
  • Repeat : create channel, put values into the channel repeatly until cancel the context. [doc] [play]
  • RepeatFn : create a channel, excutes fn repeatly, and put the result into the channel, until close context. [doc] [play]
  • Take : create a channel whose values are taken from another channel with limit number. [doc] [play]
  • Tee : split one chanel into two channels, until cancel the context. [doc] [play]

4. Condition package contains some functions for conditional judgment. eg. And, Or, TernaryOperator...

import "github.com/duke-git/lancet/v2/condition"

Function list:

  • Bool : returns the truthy value of anything. [doc] [play]
  • And : returns true if both a and b are truthy. [doc] [play]
  • Or : returns false if neither a nor b is truthy. [doc] [play]
  • Xor : returns true if a or b but not both is truthy. [doc] [play]
  • Nor : returns true if neither a nor b is truthy. [doc] [play]
  • Xnor : returns true if both a and b or neither a nor b are truthy. [doc] [play]
  • Nand : returns false if both a and b are truthy. [doc] [play]
  • TernaryOperator : ternary operator. [doc] [play]

5. Convertor package contains some functions for data convertion.

import "github.com/duke-git/lancet/v2/convertor"

Function list:

  • ColorHexToRGB : convert color hex to color rgb. [doc] [play]
  • ColorRGBToHex : convert rgb color to hex color. [doc] [play]
  • ToBool : convert string to bool. [doc] [play]
  • ToBytes : convert value to byte slice. [doc] [play]
  • ToChar : convert string to char slice. [doc] [play]
  • ToChannel : convert a collection of elements to a read-only channel. [doc] [play]
  • ToFloat : convert value to float64, if param is a invalid floatable, will return 0.0 and error. [doc] [play]
  • ToInt : convert value to int64 value, if input is not numerical, return 0 and error. [doc] [play]
  • ToJson : convert value to a json string. [doc] [play]
  • ToMap : convert a slice of structs to a map based on iteratee function. [doc] [play]
  • ToPointer : return a pointer of passed value. [doc] [play]
  • ToString : convert value to string. [doc] [play]
  • StructToMap : convert struct to map, only convert exported struct field. [doc] [play]
  • MapToSlice : convert map to slice based on iteratee function. [doc] [play]
  • EncodeByte : encode data to byte slice. [doc] [play]
  • DecodeByte : decode byte slice data to target object. [doc] [play]
  • DeepClone : creates a deep copy of passed item, can't clone unexported field of struct. [doc] [play]
  • CopyProperties : copies each field from the source struct into the destination struct. [doc] [play]
  • ToInterface : converts reflect value to its interface type. [doc] [play]

6. Cryptor package is for data encryption and decryption.

import "github.com/duke-git/lancet/v2/cryptor"

Function list:

  • AesEcbEncrypt : encrypt byte slice data with key use AES ECB algorithm. [doc] [play]
  • AesEcbDecrypt : decrypt byte slice data with key use AES ECB algorithm. [doc] [play]
  • AesCbcEncrypt : encrypt byte slice data with key use AES CBC algorithm. [doc] [play]
  • AesCbcDecrypt : decrypt byte slice data with key use AES CBC algorithm. [doc] [play]
  • AesCtrCrypt : encrypt/ decrypt byte slice data with key use AES CRC algorithm. [doc] [play]
  • AesCfbEncrypt : encrypt byte slice data with key use AES CFB algorithm. [doc] [play]
  • AesCfbDecrypt : decrypt byte slice data with key use AES CFB algorithm. [doc] [play]
  • AesOfbEncrypt : encrypt byte slice data with key use AES OFB algorithm. [doc] [play]
  • AesOfbDecrypt : decrypt byte slice data with key use AES OFB algorithm. [doc] [play]
  • Base64StdEncode : encode string with base64 encoding. [doc] [play]
  • Base64StdDecode : decode string with base64 encoding. [doc] [play]
  • DesEcbEncrypt : encrypt byte slice data with key use DES ECB algorithm. [doc] [play]
  • DesEcbDecrypt : decrypt byte slice data with key use DES ECB algorithm. [doc] [play]
  • DesCbcEncrypt : encrypt byte slice data with key use DES CBC algorithm. [doc] [play]
  • DesCbcDecrypt : decrypt byte slice data with key use DES CBC algorithm. [doc] [play]
  • DesCtrCrypt : encrypt/decrypt byte slice data with key use DES CRY algorithm. [doc] [play]
  • DesCfbEncrypt : encrypt byte slice data with key use DES CFB algorithm. [doc] [play]
  • DesCfbDecrypt : decrypt byte slice data with key use DES CFB algorithm. [doc] [play]
  • DesOfbEncrypt : encrypt byte slice data with key use DES OFB algorithm. [doc] [play]
  • DesOfbDecrypt : decrypt byte slice data with key use DES OFB algorithm. [doc] [play]
  • HmacMd5 : return the md5 hmac hash of string. [doc] [play]
  • HmacSha1 : return the hmac hash of string use sha1. [doc] [play]
  • HmacSha256 : return the hmac hash of string use sha256. [doc] [play]
  • HmacSha512 : return the hmac hash of string use sha512. [doc] [play]
  • Md5String : return the md5 value of string. [doc] [play]
  • Md5File : return the md5 value of file. [doc]
  • Sha1 : return the sha1 value (SHA-1 hash algorithm) of string. [doc] [play]
  • Sha256 : return the sha256 value (SHA-256 hash algorithm) of string. [doc] [play]
  • Sha512 : return the sha512 value (SHA-512 hash algorithm) of string. [doc] [play]
  • GenerateRsaKey : create rsa private and public pemo file. [doc] [play]
  • RsaEncrypt : encrypt data with ras algorithm. [doc] [play]
  • RsaDecrypt : decrypt data with ras algorithm. [doc] [play]

7. Datetime package supports date and time format and compare.

import "github.com/duke-git/lancet/v2/datetime"

Function list:

  • AddDay : add or sub day to the time. [doc] [play]
  • AddHour : add or sub day to the time. [doc] [play]
  • AddMinute : add or sub day to the time. [doc] [play]
  • AddYear : add or sub year to the time. [doc] [play]
  • BeginOfMinute : return the date time at the begin of minute of specific date. [doc] [play]
  • BeginOfHour : return the date time at the begin of hour of specific date. [doc] [play]
  • BeginOfDay : return the date time at the begin of day of specific date. [doc] [play]
  • BeginOfWeek : return the date time at the begin of week of specific date. [doc] [play]
  • BeginOfMonth : return the date time at the begin of month of specific date. [doc] [play]
  • BeginOfYear : return the date time at the begin of year of specific date. [doc] [play]
  • EndOfMinute : return the date time at the end of minute of specific date. [doc] [play]
  • EndOfHour : return the date time at the end of hour of specific date. [doc] [play]
  • EndOfDay : return the date time at the end of day of specific date. [doc] [play]
  • EndOfWeek : return the date time at the end of week of specific date. [doc] [play]
  • EndOfMonth : return the date time at the end of month of specific date. [doc] [play]
  • EndOfYear : return the date time at the end of year of specific date. [doc] [play]
  • GetNowDate : return format yyyy-mm-dd of current date. [doc] [play]
  • GetNowTime : return format hh-mm-ss of current time. [doc] [play]
  • GetNowDateTime : return format yyyy-mm-dd hh-mm-ss of current datetime. [doc] [play]
  • GetZeroHourTimestamp : return timestamp of zero hour (timestamp of 00:00). [doc] [play]
  • GetNightTimestamp : return timestamp of zero hour (timestamp of 23:59). [doc] [play]
  • FormatTimeToStr : convert time to string. [doc] [play]
  • FormatStrToTime : convert string to time. [doc] [play]
  • NewUnix : return unix timestamp of specific time. [doc] [play]
  • NewUnixNow : return unix timestamp of current time. [doc] [play]
  • NewFormat : return unix timestamp of specific time string, t should be "yyyy-mm-dd hh:mm:ss". [doc] [play]
  • NewISO8601 : return unix timestamp of specific iso8601 time string. [doc] [play]
  • ToUnix : return unix timestamp. [doc] [play]
  • ToFormat : return the time string 'yyyy-mm-dd hh:mm:ss' of unix time. [doc] [play]
  • ToFormatForTpl : return the time string which format is specific tpl. [doc] [play]
  • ToIso8601 : return iso8601 time string. [doc] [play]
  • IsLeapYear : check if param year is leap year or not. [doc] [play]

8. Datastructure package constains some common data structure. eg. list, linklist, stack, queue, set, tree, graph.

import list "github.com/duke-git/lancet/v2/datastructure/list"
import link "github.com/duke-git/lancet/v2/datastructure/link"
import stack "github.com/duke-git/lancet/v2/datastructure/stack"
import queue "github.com/duke-git/lancet/v2/datastructure/queue"
import set "github.com/duke-git/lancet/v2/datastructure/set"
import tree "github.com/duke-git/lancet/v2/datastructure/tree"
import heap "github.com/duke-git/lancet/v2/datastructure/heap"
import hashmap "github.com/duke-git/lancet/v2/datastructure/hashmap"

Structure list:

  • List : a linear table, implemented with slice. [doc]
  • Link : link list structure, contains singly link and doubly link. [doc]
  • Stack : stack structure(fifo), contains array stack and link stack. [doc]
  • Queue : queue structure(filo), contains array queue, circular queue, link queue and priority queue. [doc]
  • Set : a data container, like slice, but element of set is not duplicate. [doc]
  • Tree : binary search tree structure. [doc]
  • Heap : a binary max heap. [doc]
  • Hashmap : hash map structure. [doc]

9. Fileutil package implements some basic functions for file operations.

import "github.com/duke-git/lancet/v2/fileutil"

Function list:

  • ClearFile : write empty string to target file. [doc] [play]
  • CreateFile : create file in path. [doc] [play]
  • CreateDir : create directory in absolute path. [doc] [play]
  • CopyFile :copy src file to dest file. [doc] [play]
  • FileMode : return file's mode and permission. [doc] [play]
  • MiMeType : return file mime type. [doc] [play]
  • IsExist : checks if a file or directory exists. [doc] [play]
  • IsLink : checks if a file is symbol link or not. [doc] [play]
  • IsDir : checks if the path is directory or not. [doc] [play]
  • ListFileNames : return all file names in the path. [doc] [play]
  • RemoveFile : remove file, param should be file path. [doc] [play]
  • ReadFileToString : return string of file content. [doc] [play]
  • ReadFileByLine : read file line by line, return string slice of file content. [doc] [play]
  • Zip : create zip file. [doc] [play]
  • UnZip : unzip the zip file and save it to dest path. [doc] [play]
  • CurrentPath : return current absolute path. [doc] [play]
  • IsZipFile : checks if file is zip file or not. [doc] [play]
  • FileSize : return file size in bytes. [doc] [play]
  • MTime : return file modified time(unix timestamp). [doc] [play]
  • Sha : return file sha value. [doc] [play]
  • ReadCsvFile : read file content into slice. [doc] [play]

10. Formatter contains some functions for data formatting.

import "github.com/duke-git/lancet/v2/formatter"

Function list:

  • Comma : add comma to a number value by every 3 numbers from right, ahead by symbol char. [doc] [play]
  • Pretty : pretty print data to JSON string. [doc] [play]
  • PrettyToWriter : pretty encode data to writer. [doc] [play]
  • DecimalBytes : returns a human readable byte size under decimal standard (base 1000). [doc] [play]
  • BinaryBytes : returns a human-readable byte size under binary standard (base 1024). [doc] [play]
  • ParseDecimalBytes : return the human readable bytes size string into the amount it represents(base 1000). [doc] [play]
  • ParseBinaryBytes : return the human readable bytes size string into the amount it represents(base 1024). [doc] [play]

11. Function package can control the flow of function execution and support part of functional programming

import "github.com/duke-git/lancet/v2/function"

Function list:

  • After : return a function that invokes passed funcation once the returned function is called more than n times. [doc] [play]
  • Before : return a function that invokes passed funcation once the returned function is called less than n times [doc] [play]
  • CurryFn : make a curry function. [doc] [play]
  • Compose : compose the functions from right to left. [doc] [play]
  • Delay : call the function after delayed time. [doc] [play]
  • Debounced : creates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked. [doc] [play]
  • Schedule : invoke function every duration time, util close the returned bool channel. [doc] [play]
  • Pipeline : takes a list of functions and returns a function whose param will be passed into the functions one by one. [doc] [play]
  • Watcher : Watcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution. [doc] [play]

12. Maputil package includes some functions to manipulate map.

import "github.com/duke-git/lancet/v2/maputil"

Function list:

  • MapTo : quick map any value to struct or any base type. [doc] [play]
  • ForEach : executes iteratee funcation for every key and value pair in map. [doc] [play]
  • Filter : iterates over map, return a new map contains all key and value pairs pass the predicate function. [doc] [play]
  • FilterByKeys : iterates over map, return a new map whose keys are all given keys [doc] [play]
  • FilterByValues : iterates over map, return a new map whose values are all given values. [doc] [play]
  • OmitBy : the opposite of Filter, removes all the map elements for which the predicate function returns true. [doc] [play]
  • OmitByKeys : the opposite of FilterByKeys, extracts all the map elements which keys are not omitted. [doc] [play]
  • OmitByValues : the opposite of FilterByValues. remov all elements whose value are in the give slice. [doc] [play]
  • Intersect : iterates over maps, return a new map of key and value pairs in all given maps. [doc] [play]
  • Keys : returns a slice of the map's keys. [doc] [play]
  • KeysBy : creates a slice whose element is the result of function mapper invoked by every map's key. [doc] [play]
  • Merge : merge maps, next key will overwrite previous key. [doc] [play]
  • Minus : creates a map of whose key in mapA but not in mapB. [doc] [play]
  • Values : returns a slice of the map's values. [doc] [play]
  • ValuesBy : creates a slice whose element is the result of function mapper invoked by every map's value. [doc] [play]
  • MapKeys : transforms a map to other type map by manipulating it's keys. [doc] [play]
  • MapValues : transforms a map to other type map by manipulating it's values. [doc] [play]
  • Entries : transforms a map into array of key/value pairs. [doc] [play]
  • FromEntries : creates a map based on a slice of key/value pairs. [doc] [play]
  • Transform : transform a map to another type map. [doc] [play]
  • IsDisjoint : check two map are disjoint if they have no keys in common. [doc] [play]

13. Mathutil package implements some functions for math calculation.

import "github.com/duke-git/lancet/v2/mathutil"

Function list:

  • Average :return average value of numbers. [doc] [play]
  • Exponent : calculate x^n for int64. [doc] [play]
  • Fibonacci :calculate fibonacci number before n for int. [doc] [play]
  • Factorial : calculate x! for uint. [doc] [play]
  • Max : return maximum value of numbers. [doc] [play]
  • MaxBy : return the maximum value of a slice using the given comparator function. [doc] [play]
  • Min : return minimum value of numbers. [doc] [play]
  • MinBy : return the minimum value of a slice using the given comparator function. [doc] [play]
  • Percent : calculate the percentage of value to total. [doc] [play]
  • RoundToFloat : round up to n decimal places for float64. [doc] [play]
  • RoundToString : round up to n decimal places for float64, return string. [doc] [play]
  • TruncRound : round off n decimal places for int64. [doc] [play]
  • Range : Creates a slice of numbers from start with specified count, element step is 1. [doc] [play]
  • RangeWithStep : Creates a slice of numbers from start to end with specified step. [doc] [play]
  • AngleToRadian : converts angle value to radian value. [doc] [play]
  • RadianToAngle : converts radian value to angle value. [doc] [play]
  • PointDistance : get two points distance. [doc] [play]
  • IsPrime : checks if number is prime number. [doc] [play]
  • GCD : return greatest common divisor (GCD) of integers. [doc] [play]
  • LCM : return Least Common Multiple (LCM) of integers. [doc] [play]

14. Netutil package contains functions to get net information and send http request.

import "github.com/duke-git/lancet/v2/netutil"

Function list:

  • ConvertMapToQueryString : convert map to sorted url query string. [doc] [play]
  • EncodeUrl : encode url(?a=1&b=[2] -> ?a=1&b=%5B2%5D). [doc] [play]
  • GetInternalIp : return internal ipv4. [doc] [play]
  • GetIps : return all ipv4 of current system. [doc] [play]
  • GetMacAddrs : return mac address of current system. [doc] [play]
  • GetPublicIpInfo : return public ip information. [doc] [play]
  • GetRequestPublicIp : return the http request public ip. [doc] [play]
  • IsPublicIP : verify a ip is public or not. [doc] [play]
  • IsInternalIP : verify an ip is intranet or not. [doc] [play]
  • HttpRequest : a composed http request used for HttpClient send request. [doc] [play]
  • HttpClient : a http client tool, used for sending http request [doc] [play]
  • SendRequest : send http request. [doc] [play]
  • DecodeResponse : decode http response into target object. [doc] [play]
  • StructToUrlValues : convert struct to url valuse. [doc] [play]
  • HttpGetdeprecated : send http get request. [doc]
  • HttpDeletedeprecated : send http delete request. [doc]
  • HttpPostdeprecated : send http post request. [doc]
  • HttpPutdeprecated : send http put request. [doc]
  • HttpPatchdeprecated : send http patch request. [doc]
  • ParseHttpResponse : decode http response into target object. [doc]
  • DownloadFile : download the file exist in url to a local file. [doc]
  • UploadFile : upload the file to a server. [doc]
  • IsPingConnected : checks if can ping the specified host or not. [doc] [play]
  • IsTelnetConnected : checks if can if can telnet the specified host or not. [doc] [play]

15. Random package implements some basic functions to generate random int and string.

import "github.com/duke-git/lancet/v2/random"

Function list:

  • RandBytes : generate random byte slice. [doc] [play]
  • RandInt : generate random int number between min and max. [doc] [play]
  • RandString : generate random string of specific length. [doc] [play]
  • RandUpper : generate a random upper case string. [doc] [play]
  • RandLower : generate a random lower case string. [doc] [play]
  • RandNumeral : generate a random numeral string of specific length. [doc] [play]
  • RandNumeralOrLetter : generate a random numeral or letter string. [doc] [play]
  • UUIdV4 : generate a random UUID of version 4 according to RFC 4122. [doc] [play]

16. Retry package is for executing a function repeatedly until it was successful or canceled by the context.

import "github.com/duke-git/lancet/v2/retry"

Function list:

  • Context : set retry context config option. [doc] [play]
  • Retry : executes the retryFunc repeatedly until it was successful or canceled by the context. [doc] [play]
  • RetryFunc : function that retry executes. [doc] [play]
  • RetryDuration : set duration of retry [doc] [play]
  • RetryTimes : set times of retry. [doc] [play]

17. Slice contains some functions to manipulate slice.

import "github.com/duke-git/lancet/v2/slice"

Function list:

  • AppendIfAbsent : if the item is absent,append it to the slice. [doc] [play]
  • Contain : check if the value is in the slice or not. [doc] [play]
  • ContainBy : returns true if predicate function return true. [doc] [play]
  • ContainSubSlice : check if the slice contain a given subslice or not. [doc] [play]
  • Chunk : creates a slice of elements split into groups the length of size. [doc] [play]
  • Compact : creates an slice with all falsey values removed. The values false, nil, 0, and "" are falsey. [doc] [play]
  • Concat : creates a new slice concatenating slice with any additional slices. [doc] [play]
  • Count : returns the number of occurrences of the given item in the slice. [doc] [play]
  • CountBy : iterates over elements of slice with predicate function, returns the number of all matched elements. [doc] [play]
  • Difference : creates an slice of whose element in slice but not in compared slice. [doc] [play]
  • DifferenceBy : accepts iteratee which is invoked for each element of slice and values to generate the criterion by which they're compared. [doc] [play]
  • DifferenceWith : accepts comparator which is invoked to compare elements of slice to values. [doc] [play]
  • DeleteAt : delete the element of slice from specific start index to end index - 1. [doc] [play]
  • Drop : drop n elements from the start of a slice. [doc] [play]
  • DropRight : drop n elements from the end of a slice. [doc] [play]
  • DropWhile : drop n elements from the start of a slice while predicate function returns true. [doc] [play]
  • DropRightWhile : drop n elements from the end of a slice while predicate function returns true. [doc] [play]
  • Equal : checks if two slices are equal: the same length and all elements' order and value are equal. [doc] [play]
  • EqualWith : checks if two slices are equal with comparator func. [doc] [play]
  • Every : return true if all of the values in the slice pass the predicate function. [doc] [play]
  • Filter : iterates over elements of slice, returning an slice of all elements pass the predicate function. [doc] [play]
  • FilterMap : returns a slice which apply both filtering and mapping to the given slice. [doc] [play]
  • Finddeprecated : iterates over elements of slice, returning the first one that passes a truth test on predicate function. [doc] [play]
  • FindBy : iterates over elements of slice, returning the first one that passes a truth test on predicate function. [doc] [play]
  • FindLastdeprecated : return the last item that passes a truth test on predicate function. [doc] [play]
  • FindLastBy : iterates over elements of slice, returning the last one that passes a truth test on predicate function. [doc] [play]
  • Flatten : flattens slice one level. [doc] [play]
  • FlattenDeep : flattens slice recursive to one level. [doc] [play]
  • FlatMap : manipulates a slice and transforms and flattens it to a slice of another type. [doc] [play]
  • ForEach : iterates over elements of slice and invokes function for each element. [doc] [play]
  • ForEachWithBreak : iterates over elements of slice and invokes function for each element, when iteratee return false, will break the for each loop. [doc] [play]
  • GroupBy : iterate over elements of the slice, each element will be group by criteria, returns two slices. [doc] [play]
  • GroupWith : return a map composed of keys generated from the resultults of running each element of slice thru iteratee. [doc] [play]
  • IntSlicedeprecated : convert param to int slice. [doc] [play]
  • InterfaceSlicedeprecated : convert param to interface slice. [doc] [play]
  • Intersection : creates a slice of unique elements that included by all slices. [doc] [play]
  • InsertAt : insert the value or other slice into slice at index. [doc] [play]
  • IndexOf : returns the index at which the first occurrence of an item is found in a slice. [doc] [play]
  • LastIndexOf : returns the index at which the last occurrence of the item is found in a slice. [doc] [play]
  • Map : creates an slice of values by running each element of slice thru iteratee function. [doc] [play]
  • Merge : merge all given slices into one slice. [doc] [play]
  • Reverse : return slice of element order is reversed to the given slice. [doc] [play]
  • Reducedeprecated : creates an slice of values by running each element of slice thru iteratee function.(Deprecated: use ReduceBy) [doc] [play]
  • ReduceBy : produces a value from slice by accumulating the result of each element as passed through the reducer function. [doc] [play]
  • ReduceRight : ReduceRight is like ReduceBy, but it iterates over elements of slice from right to left. [doc] [play]
  • Replace : returns a copy of the slice with the first n non-overlapping instances of old replaced by new. [doc] [play]
  • ReplaceAll : returns a copy of the slice with all non-overlapping instances of old replaced by new. [doc] [play]
  • Repeat : creates a slice with length n whose elements are passed item. [doc] [play]
  • Shuffle : shuffle the slice. [doc] [play]
  • IsAscending : Checks if a slice is ascending order. [doc] [play]
  • IsDescending : Checks if a slice is descending order. [doc] [play]
  • IsSorted : Checks if a slice is sorted (ascending or descending). [doc] [play]
  • IsSortedByKey : Checks if a slice is sorted by iteratee function. [doc] [play]
  • Sort : sorts a slice of any ordered type(number or string). [doc] [play]
  • SortBy : sorts the slice in ascending order as determined by the less function. [doc] [play]
  • SortByFielddeprecated : return sorted slice by specific field. [doc] [play]
  • Some : return true if any of the values in the list pass the predicate function. [doc] [play]
  • StringSlicedeprecated : convert param to slice of string. [doc] [play]
  • SymmetricDifference : the symmetric difference of two slice, also known as the disjunctive union. [doc] [play]
  • ToSlice : returns a slices of a variable parameter transformation. [doc] [play]
  • ToSlicePointer : returns a pointer to the slices of a variable parameter transformation. [doc] [play]
  • Unique : remove duplicate elements in slice. [doc] [play]
  • UniqueBy : call iteratee func with every item of slice, then remove duplicated. [doc] [play]
  • Union : creates a slice of unique elements, in order, from all given slices. [doc] [play]
  • UnionBy : accepts iteratee which is invoked for each element of each slice, then union slice. [doc] [play]
  • UpdateAt : update the slice element at index. [doc] [play]
  • Without : creates a slice excluding all given items. [doc] [play]
  • KeyBy : converts a slice to a map based on a callback function. [doc] [play]

18. Stream package implements a sequence of elements supporting sequential and operations. this package is an experiment to explore if stream in go can work as the way java does. its function is very limited.

import "github.com/duke-git/lancet/v2/stream"

Function list:

  • Of : creates a stream whose elements are the specified values. [doc] [play]
  • FromSlice : creates a stream from slice. [doc] [play]
  • FromChannel : creates a stream from channel. [doc] [play]
  • FromRange : creates a number stream from start to end. both start and end are included. [start, end] [doc] [play]
  • Generate : creates a stream where each element is generated by the provided generater function. [doc] [play]
  • Concat : creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream. [doc] [play]
  • Distinct : creates returns a stream that removes the duplicated items. [doc] [play]
  • Filter : returns a stream consisting of the elements of this stream that match the given predicate. [doc] [play]
  • Map : returns a stream consisting of the elements of this stream that apply the given function to elements of stream. [doc] [play]
  • Peek : returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. [doc] [play]
  • Skip : returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. [doc] [play]
  • Limit : returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. [doc] [play]
  • Reverse : returns a stream whose elements are reverse order of given stream. [doc] [play]
  • Range : returns a stream whose elements are in the range from start(included) to end(excluded) original stream. [doc] [play]
  • Sorted : returns a stream consisting of the elements of this stream, sorted according to the provided less function. [doc] [play]
  • ForEach : performs an action for each element of this stream. [doc] [play]
  • Reduce : performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any. [doc] [play]
  • FindFirst : returns the first element of this stream and true, or zero value and false if the stream is empty. [doc] [play]
  • FindLast : returns the last element of this stream and true, or zero value and false if the stream is empty. [doc] [play]
  • Max : returns the maximum element of this stream according to the provided less function. less fuction: a > b [doc] [play]
  • Min : returns the minimum element of this stream according to the provided less function. less fuction: a < b [doc] [play]
  • AllMatch : returns whether all elements of this stream match the provided predicate. [doc] [play]
  • AnyMatch : returns whether any elements of this stream match the provided predicate. [doc] [play]
  • NoneMatch : returns whether no elements of this stream match the provided predicate. [doc] [play]
  • Count : returns the count of elements in the stream. [doc] [play]
  • ToSlice : returns the elements in the stream. [doc] [play]

19. Structs package provides several high level functions to manipulate struct, tag, and field.

import "github.com/duke-git/lancet/v2/structs"

Function list:

  • New : creates a Struct instance. [doc]
  • ToMap : converts a valid struct to a map. [doc]
  • Fields : get all fields of a given struct, that the fields are abstract struct field. [doc]
  • IsStruct : check if the struct is valid. [doc]
  • Tag : get a Tag of the Field, Tag is a abstract struct field tag [doc]
  • Name : get the field name. [doc]
  • Value : get the Field underlying value. [doc]
  • Kind : get the field's kind [doc]
  • IsEmbedded : check if the field is an embedded field. [doc]
  • IsExported : check if the field is exporte [doc]
  • IsZero : check if the field is zero value [doc]
  • IsSlice : check if the field is a slice [doc]

20. Strutil package contains some functions to manipulate string.

import "github.com/duke-git/lancet/v2/strutil"

Function list:

  • After : returns the substring after the first occurrence of a specific string in the source string. [doc] [play]
  • AfterLast : returns the substring after the last occurrence of a specific string in the source string. [doc] [play]
  • Before : returns the substring before the first occurrence of a specific string in the source string. [doc] [play]
  • BeforeLast : returns the substring before the last occurrence of a specific string in the source string. [doc] [play]
  • CamelCase : coverts source string to its camelCase string. [doc] [play]
  • Capitalize : converts the first character of source string to upper case and the remaining to lower case. [doc] [play]
  • IsString : checks if the parameter value data type is string or not. [doc] [play]
  • KebabCase : coverts string to kebab-case string. [doc] [play]
  • UpperKebabCase : coverts string to upper KEBAB-CASE string. [doc] [play]
  • LowerFirst : converts the first character of string to lower case. [doc] [play]
  • UpperFirst : converts the first character of string to upper case. [doc] [play]
  • Pad : pads string on the left and right side if it's shorter than size. [doc] [play]
  • PadEnd : pads string with given characters on the right side if it's shorter than limit size. Padding characters are truncated if they exceed size. [doc] [play]
  • PadStart : pads string with given characters on the left side if it's shorter than limit size. Padding characters are truncated if they exceed size. [doc] [play]
  • Reverse : returns string whose char order is reversed to the given string. [doc] [play]
  • SnakeCase : coverts string to snake_case string. [doc] [play]
  • UpperSnakeCase : coverts string to upper SNAKE_CASE string. [doc] [play]
  • SplitEx : split a given string which can control the result slice contains empty string or not. [doc] [play]
  • Substring : returns a substring of the specific length starting at the specific offset position. [doc] [play]
  • Wrap : wrap a string with given string. [doc] [play]
  • Unwrap : unwrap a given string from anther string. will change source string. [doc] [play]
  • SplitWords : splits a string into words, word only contains alphabetic characters. [doc] [play]
  • WordCount : return the number of meaningful word of a string, word only contains alphabetic characters. [doc] [play]
  • RemoveNonPrintable : remove non-printable characters from a string. [doc] [play]
  • StringToBytes : converts a string to byte slice without a memory allocation. [doc] [play]
  • BytesToString : converts a byte slice to string without a memory allocation. [doc] [play]
  • IsBlank : checks if a string is whitespace or empty. [doc] [play]
  • HasPrefixAny : checks if a string starts with any of an array of specified strings. [doc] [play]
  • HasSuffixAny : checks if a string ends with any of an array of specified strings. [doc] [play]
  • IndexOffset : returns the index of the first instance of substr in string after offsetting the string by idxFrom. [doc] [play]
  • ReplaceWithMap : returns a copy of str, which is replaced by a map in unordered way, case-sensitively. [doc] [play]
  • Trim : strips whitespace (or other characters) from the beginning and end of a string. [doc] [play]
  • SplitAndTrim : splits string str by a string delimiter to a slice, and calls Trim to every element of slice. [doc] [play]

21. System package contain some functions about os, runtime, shell command.

import "github.com/duke-git/lancet/v2/system"

Function list:

  • IsWindows : check if current os is windows. [doc] [play]
  • IsLinux : check if current os is linux. [doc] [play]
  • IsMac : check if current os is macos. [doc] [play]
  • GetOsEnv : get the value of the environment variable named by the key. [doc] [play]
  • SetOsEnv : set the value of the environment variable named by the key. [doc] [play]
  • RemoveOsEnv : remove a single environment variable. [doc] [play]
  • CompareOsEnv : get env named by the key and compare it with passed env. [doc] [play]
  • ExecCommand : execute command, return the stdout and stderr string of command, and error if error occurs. [doc] [play]
  • GetOsBits : return current os bits (32 or 64). [doc] [play]

22. Validator package contains some functions for data validation.

import "github.com/duke-git/lancet/v2/validator"

Function list:

  • ContainChinese : check if the string contain mandarin chinese. [doc] [play]
  • ContainLetter : check if the string contain at least one letter. [doc] [play]
  • ContainLower : check if the string contain at least one lower case letter a-z. [doc] [play]
  • ContainUpper : check if the string contain at least one upper case letter A-Z. [doc] [play]
  • IsAlpha : checks if the string contains only letters (a-zA-Z). [doc] [play]
  • IsAllUpper : check if the string is all upper case letters A-Z. [doc] [play]
  • IsAllLower : check if the string is all lower case letters a-z. [doc] [play]
  • IsBase64 : check if the string is base64 string. [doc] [play]
  • IsChineseMobile : check if the string is chinese mobile number. [doc] [play]
  • IsChineseIdNum : check if the string is chinese id card. [doc] [play]
  • IsChinesePhone : check if the string is chinese phone number.(xxx-xxxxxxxx or xxxx-xxxxxxx.) [doc] [play]
  • IsCreditCard : check if the string is credit card. [doc] [play]
  • IsDns : check if the string is dns. [doc] [play]
  • IsEmail : check if the string is a email address. [doc] [play]
  • IsEmptyString : check if the string is empty. [doc] [play]
  • IsFloat : check if the value is float(float32, float34) or not. [doc] [play]
  • IsFloatStr : check if the string can convert to a float. [doc] [play]
  • IsNumber : check if the value is number(integer, float) or not. [doc] [play]
  • IsNumberStr : check if the string can convert to a number. [doc] [play]
  • IsJSON : check if the string is valid JSON. [doc] [play]
  • IsRegexMatch : check if the string match the regexp. [doc] [play]
  • IsInt : check if the string can convert to a number. [doc] [play]
  • IsIntStr : check if the string can convert to a integer. [doc] [play]
  • IsIp : check if the string is ip. [doc] [play]
  • IsIpV4 : check if the string is ipv4. [doc] [play]
  • IsIpV6 : check if the string is ipv6. [doc] [play]
  • IsStrongPassword : check if the string is strong password. [doc] [play]
  • IsUrl : check if the string is url. [doc] [play]
  • IsWeakPassword : check if the string is weak password. [doc] [play]
  • IsZeroValue : check if value is a zero value. [doc] [play]
  • IsGBK : check if data encoding is gbk. [doc] [play]
  • IsASCII : checks if string is all ASCII char. [doc] [play]
  • IsPrintable : checks if string is all printable chars. [doc] [play]

23. xerror package implements helpers for errors.

import "github.com/duke-git/lancet/v2/xerror"

Function list:

  • New : creates a new XError pointer instance with message. [doc] [play]
  • Wrap : creates a new XError pointer instance based on error object, and add message. [doc] [play]
  • Unwrap : returns unwrapped XError from err by errors.As. If no XError, returns nil. [doc] [play]
  • XError_Wrap : creates a new XError and copy message and id to new one. [doc] [play]
  • XError_Unwrap : Compatible with github.com/pkg/errors. [doc] [play]
  • XError_With : adds key and value related to the XError object. [doc] [play]
  • XError_Id : sets XError object id to check equality in XError.Is. [doc] [play]
  • XError_Is : checks if target error is XError and Error.id of two errors are matched. [doc] [play]
  • XError_Values : returns map of key and value that is set by XError.With function. [doc] [play]
  • XError_StackTrace : returns stack trace which is compatible with pkg/errors. [doc] [play]
  • XError_Info : returns information of xerror, which can be printed. [doc] [play]
  • XError_Error : implements standard error interface. [doc] [play]
  • TryUnwrap : check if err is nil then it returns a valid value. If err is not nil, TryUnwrap panics with err. [doc] [play]

How to Contribute

I really appreciate any code commits which make lancet lib powerful. Please follow the rules below to create your pull request.

  1. Fork the repository.
  2. Create your feature branch.
  3. Commit your changes.
  4. Push to the branch
  5. Create new pull request.