filter

package module
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2025 License: MIT Imports: 16 Imported by: 1

README

Golang Filter Package

The filter package offers a rich set of utilities for Go developers, focusing on string manipulation, array and slice operations, date and time formatting, number formatting, and mathematical computations. Its goal is to simplify handling common programming tasks. Below is an outline of available features and instructions for getting started.

Table of Contents


Installing

Install the filter package with ease using the following Go command:

go get github.com/kaptinlin/filter

Basic Usage

Below is an example illustrating the basic usage of the filter package for string manipulation:

package main

import (
    "fmt"
    "github.com/kaptinlin/filter"
)

func main() {
    fmt.Println(filter.Trim("  hello world  ")) // "hello world"
    fmt.Println(filter.Replace("hello world", "world", "Go")) // "hello Go"
}

String Functions

The string Functions provide a range of functions to manipulate and query strings effectively.

Function Description
Default Returns a default value if the string is empty.
Trim Removes leading and trailing whitespace from the string.
Split Divides a string into a slice of strings based on a specified delimiter.
Replace Substitutes all instances of a specified substring with another string.
Remove Eliminates all occurrences of a specified substring from the string.
Append Adds characters to the end of a string.
Prepend Adds characters to the beginning of a string.
Length Returns the number of characters in a string, accounting for UTF-8 encoding.
Upper Converts all characters in a string to uppercase.
Lower Converts all characters in a string to lowercase.
Titleize Capitalizes the first letter of each word in a string.
Capitalize Capitalizes the first letter of a string.
Camelize Converts a string to camelCase.
Pascalize Converts a string to PascalCase.
Dasherize Transforms a string into a lowercased, dash-separated format.
Slugify Converts a string into a URL-friendly "slug", ensuring it is safe for use in URLs and filenames.
Pluralize Determines the singular or plural form of a word based on a numeric value.
Ordinalize Converts a number to its ordinal English form.
Truncate Shortens a string to a specified length and appends "..." if it exceeds that length.
TruncateWords Truncates a string to a specified number of words, appending "..." if it exceeds that limit.

Array Functions

Array functions help you work with slices, offering tools to modify, analyze, or transform slice data.

Function Description
Unique Removes duplicate elements, leaving only unique ones.
Join Concatenates slice elements into a single string.
First Retrieves the first element of the slice.
Last Returns the last element of the slice.
Random Selects a random element from the slice.
Reverse Reverses the order of elements in the slice.
Shuffle Randomly rearranges the elements within the slice.
Size Determines the size (length) of the slice.
Max Identifies the maximum value in a numerical slice.
Min Finds the minimum value in a numerical slice.
Sum Calculates the sum of all elements in a numerical slice.
Average Computes the average value of a numerical slice.
Map Extracts a slice of values for a specified key.

Date Functions

Date functions facilitate working with dates, including formatting, parsing, and manipulation.

Function Description
Date Formats a timestamp into a specified format or returns a default datetime string.
Day Extracts and returns the day of the month.
Month Retrieves the month number from a date.
MonthFull Returns the full month name from a date.
Year Extracts and returns the year from a date.
Week Returns the ISO week number of a date.
Weekday Determines the day of the week from a date.
TimeAgo Provides a human-readable string representing the time difference to the present.
Number Functions

Number functions allows for the formatting of numbers for presentation and readability.

Function Description
Number Formats any numeric value based on a specified format string.
Bytes Converts a numeric value into a human-readable format representing bytes.
Math Functions

Math functions include a variety of operations for numerical computation and manipulation.

Function Description
Abs Calculates the absolute value of a number.
AtLeast Ensures a number is at least a specified minimum.
AtMost Ensures a number does not exceed a specified maximum.
Round Rounds a number to a specified number of decimal places.
Floor Rounds a number down to the nearest whole number.
Ceil Rounds a number up to the nearest whole number.
Plus Adds two numbers together.
Minus Subtracts one number from another.
Times Multiplies two numbers.
Divide Divides one number by another, with handling for division by zero.
Modulo Calculates the remainder of division of one number by another.
Data Functions

Data functions provide utilities for extracting and manipulating data from complex nested structures including maps, slices, arrays, structs, pointers, and interfaces.

Function Description
Extract Retrieves a nested value from any supported data structure using a dot-separated key path. Supports maps, slices, arrays, structs, pointers, and complex nested combinations.

Credits

How to Contribute

Contributions to the filter package are welcome. If you'd like to contribute, please follow the contribution guidelines.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package filter provides template filter functions for string manipulation, array operations, date formatting, number formatting, and mathematical computations.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotNumeric indicates the input is not a numeric type
	ErrNotNumeric = errors.New("input is not numeric")
	// ErrInvalidTimeFormat indicates the input has an invalid time format
	ErrInvalidTimeFormat = errors.New("input has an invalid time format")
	// ErrUnsupportedType indicates the input is of an unsupported type
	ErrUnsupportedType = errors.New("input is of an unsupported type")
	// ErrNotSlice indicates the expected input should be a slice
	ErrNotSlice = errors.New("expected input to be a slice")
	// ErrEmptySlice indicates the slice is empty
	ErrEmptySlice = errors.New("slice is empty")
	// ErrInvalidArguments indicates invalid number of arguments
	ErrInvalidArguments = errors.New("invalid number of arguments")
	// ErrKeyNotFound indicates the key was not found
	ErrKeyNotFound = errors.New("key not found")
	// ErrIndexOutOfRange indicates the index is out of range
	ErrIndexOutOfRange = errors.New("index out of range")
	// ErrInvalidKeyType indicates an invalid key type
	ErrInvalidKeyType = errors.New("invalid key type")
	// ErrDivisionByZero indicates division by zero
	ErrDivisionByZero = errors.New("division by zero")
	// ErrModulusByZero indicates modulus by zero
	ErrModulusByZero = errors.New("modulus by zero")
	// ErrUnsupportedSizeType indicates the input type is not supported by the size filter
	ErrUnsupportedSizeType = errors.New("size filter expects a slice, array, or map")
)

Functions

func Abs

func Abs(input interface{}) (float64, error)

Abs calculates the absolute value of the input.

func Append

func Append(input, toAppend string) string

Append appends characters to the end of a string.

func AtLeast

func AtLeast(input interface{}, minimum interface{}) (float64, error)

AtLeast ensures the input is at least as large as the minimum value.

func AtMost

func AtMost(input interface{}, maximum interface{}) (float64, error)

AtMost ensures the input is no larger than the maximum value.

func Average

func Average(input interface{}) (float64, error)

Average calculates the average value of elements in a slice of float64.

func Bytes

func Bytes(input interface{}) (string, error)

Bytes formats a numeric value into a human-readable byte format.

func Camelize

func Camelize(input string) string

Camelize converts a string to camelCase, lowercasing the first letter of the first segment and capitalizing the first letter of each subsequent segment.

func Capitalize

func Capitalize(input string) string

Capitalize will capitalize the first letter of the string.

func Ceil

func Ceil(input interface{}) (float64, error)

Ceil rounds the input up to the nearest whole number.

func Dasherize

func Dasherize(input string) string

Dasherize converts a string to a lowercased, dashed string, removing non-alphanumeric characters.

func Date

func Date(input interface{}, format string) (string, error)

Date formats a timestamp into a specified format. Returns a string representation of the date.

func Day

func Day(input interface{}) (int, error)

Day extracts and returns the day of the month from the input date.

func Default

func Default(input, defaultValue string) string

Default sets a default value for an empty string.

func Divide

func Divide(input interface{}, divisor interface{}) (float64, error)

Divide divides the first value by the second, including error handling for division by zero.

func Extract

func Extract(input interface{}, key string) (interface{}, error)

Extract retrieves a value from input using dot-separated key notation. It supports maps, slices, arrays, structs, pointers, and interfaces.

The key uses dot notation for nested access:

  • "user.name" accesses the "name" field of "user"
  • "items.0.title" accesses the "title" field of the first item
  • "matrix.1.0" accesses element [1][0] of a 2D array

Supported input types:

  • map[string]interface{} and similar map types
  • []interface{} and other slice types
  • Arrays (including multi-dimensional)
  • Structs with json tags or exported field names
  • Pointers to any of the above
  • Interfaces containing any of the above

Returns ErrUnsupportedType if input is nil. Returns ErrKeyNotFound if the key path doesn't exist. Returns ErrIndexOutOfRange for invalid array/slice indices. Returns ErrInvalidKeyType for invalid path navigation.

func First

func First(input interface{}) (interface{}, error)

First returns the first element of a slice.

func Floor

func Floor(input interface{}) (float64, error)

Floor rounds the input down to the nearest whole number.

func Index

func Index(input interface{}, index int) (interface{}, error)

Index returns the element at a specified index in a slice.

func Join

func Join(input interface{}, separator string) (string, error)

Join joins the elements of a slice into a single string with a given separator.

func Last

func Last(input interface{}) (interface{}, error)

Last returns the last element of a slice.

func Length

func Length(input string) int

Length returns the length of the input string.

func Lower

func Lower(input string) string

Lower converts a string input to lowercase.

func Map

func Map(input interface{}, key string) ([]interface{}, error)

Map returns a slice of values for a specified key from each map in the input slice. If the key does not exist in an item, the corresponding value in the result slice will be nil.

func Max

func Max(input interface{}) (float64, error)

Max returns the maximum value from a slice of float64.

func Min

func Min(input interface{}) (float64, error)

Min returns the minimum value from a slice of float64.

func Minus

func Minus(input interface{}, subtrahend interface{}) (float64, error)

Minus subtracts the second value from the first.

func Modulo

func Modulo(input interface{}, modulus interface{}) (float64, error)

Modulo returns the remainder of the division of the first value by the second.

func Month

func Month(input interface{}) (int, error)

Month extracts and returns the month number from the input date.

func MonthFull

func MonthFull(input interface{}) (string, error)

MonthFull returns the full month name from the input date.

func Number

func Number(input interface{}, format string) (string, error)

Number formats a numeric value according to the specified format string.

func Ordinalize

func Ordinalize(number int) string

Ordinalize converts a numeric input to its ordinal English version as a string.

func Pascalize

func Pascalize(input string) string

Pascalize converts a string to PascalCase, capitalizing the first letter of each segment.

func Pluralize

func Pluralize(count int, singular, plural string) string

Pluralize outputs the singular or plural version of a string based on the value of a number.

func Plus

func Plus(input interface{}, addend interface{}) (float64, error)

Plus adds two numbers.

func Prepend

func Prepend(input, toPrepend string) string

Prepend prepends characters to the beginning of a string.

func Random

func Random(input interface{}) (interface{}, error)

Random selects a random element from a slice.

func Remove

func Remove(input, toRemove string) string

Remove removes all occurrences of a substring from a string.

func Replace

func Replace(input, old, replacement string) string

Replace replaces all occurrences of a substring with another string in the input string.

func Reverse

func Reverse(input interface{}) ([]interface{}, error)

Reverse reverses the order of elements in a slice.

func Round

func Round(input interface{}, precision interface{}) (float64, error)

Round rounds the input to the specified number of decimal places.

func Shuffle

func Shuffle(input interface{}) ([]interface{}, error)

Shuffle randomly rearranges the elements of the slice.

func Size

func Size(input interface{}) (int, error)

Size returns the size (length) of a collection (slice, array, or map). For string length, use the Length function in string.go instead.

func Slugify

func Slugify(input string) string

Slugify converts a string into a URL-friendly "slug", transliterating Unicode characters to ASCII and replacing or removing special characters.

func Split

func Split(input, delimiter string) []string

Split splits a string into a slice of strings based on a delimiter.

func Sum

func Sum(input interface{}) (float64, error)

Sum calculates the sum of all elements in a slice of float64.

func TimeAgo

func TimeAgo(input interface{}) (string, error)

TimeAgo returns a human-readable string representing the time difference between the current time and the input date.

func Times

func Times(input interface{}, multiplier interface{}) (float64, error)

Times multiplies the first value by the second.

func Titleize

func Titleize(input string) string

Titleize capitalizes the start of each part of the string.

func Trim

func Trim(input string) string

Trim strips leading and trailing whitespace from a string.

func Truncate

func Truncate(input string, maxLength int) string

Truncate truncates a string to a specified length and appends "..." if it was longer.

func TruncateWords

func TruncateWords(input string, maxWords int) string

TruncateWords truncates a string to a specified number of words and appends "..." if it was longer.

func Unique

func Unique(input interface{}) ([]interface{}, error)

Unique removes duplicate elements from a slice.

func Upper

func Upper(input string) string

Upper converts a string input to uppercase.

func Week

func Week(input interface{}) (int, error)

Week returns the ISO week number from the input date.

func Weekday

func Weekday(input interface{}) (string, error)

Weekday returns the day of the week from the input date.

func Year

func Year(input interface{}) (int, error)

Year extracts and returns the year from the input date.

Types

This section is empty.

Jump to

Keyboard shortcuts

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