filter

package module
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: MIT Imports: 21 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"
}

Contract

This package is a headless value-transformation library: no I/O, no global locale, no registry, and no application policy. Stable behavior is summarized in SPECS/00-runtime-contract.md.

String Functions

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

Function Description
Trim Removes leading and trailing whitespace.
TrimLeft Removes leading whitespace.
TrimRight Removes trailing whitespace.
Split Divides a string into a slice based on a delimiter.
Replace Substitutes all occurrences of a substring.
ReplaceFirst Replaces the first occurrence of a substring.
ReplaceLast Replaces the last occurrence of a substring.
Remove Eliminates all occurrences of a substring.
RemoveFirst Removes the first occurrence of a substring.
RemoveLast Removes the last occurrence of a substring.
Append Adds characters to the end of a string.
Prepend Adds characters to the beginning of a string.
Length Returns the character count, accounting for UTF-8.
Upper Converts all characters to uppercase.
Lower Converts all characters to lowercase.
Titleize Capitalizes the first letter of each word.
Capitalize Capitalizes the first letter, lowercases the rest.
Camelize Converts a string to camelCase.
Pascalize Converts a string to PascalCase.
Dasherize Transforms into a lowercased, dash-separated format.
Slugify Converts into a URL-friendly slug.
Pluralize Returns singular or plural form based on count.
Ordinalize Converts a number to its ordinal English form.
Truncate Shortens to a length (including ellipsis), with optional custom ellipsis.
TruncateWords Truncates to a word count, with optional custom ellipsis.
Escape HTML-escapes <, >, &, ", '.
EscapeOnce HTML-escapes without double-escaping existing entities.
StripHTML Removes HTML tags, scripts, styles, and comments.
StripNewlines Removes all newline characters.
Slice Extracts a substring or sub-slice with negative offset support.
URLEncode Percent-encodes a string for URLs.
URLDecode Decodes a percent-encoded string.
Base64Encode Encodes a string to standard Base64.
Base64Decode Decodes a standard Base64 string.
Base64URLEncode Encodes a string to URL-safe Base64.
Base64URLDecode Decodes a URL-safe Base64 string.

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.
UniqueBy Removes duplicate elements by a property.
Join Concatenates slice elements into a single string.
First Retrieves the first element of the slice.
Last Returns the last element of the slice.
Index Returns the element at a specified index.
Random Selects a random element from the slice.
RandomWithRand Selects a random element with an explicit *rand.Rand.
Reverse Reverses the order of elements.
Shuffle Randomly rearranges the elements.
ShuffleWithRand Shuffles with an explicit *rand.Rand.
Size Determines the size of a slice, array, map, or string.
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.
SumBy Calculates the sum of a numeric property.
Average Computes the average value.
Map Extracts values for a specified key from each element.
Sort Sorts in ascending order, optionally by key.
SortNatural Sorts case-insensitively, optionally by key.
Compact Removes nil elements, optionally by key.
Concat Combines two slices into one.
Where Filters keeping elements matching a property value.
WhereFunc Filters using a caller-owned predicate.
Reject Filters removing elements matching a property value.
RejectFunc Rejects using a caller-owned predicate.
Find Returns first element matching a property value.
FindIndex Returns index of first matching element (-1 if none).
Has Checks if any element matches a property criteria.
HasFunc Checks a caller-owned predicate.

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 Formats a past or future relative time difference from now.

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.

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 headless value transformations for Go callers, template engines, and other dynamic-value runtimes.

What it is: pure functions that take a runtime value and return a transformed value or an error. Strings, slices, maps, dates, and numbers.

What it is not: a SQL builder, an ORM helper, an i18n framework, an XSS sanitizer, a query DSL, or a CLI argument parser. It does no I/O. It reads no environment variables. It does not consult a global locale or timezone. Functions that need "now" use SystemClock by default and expose Clock-injected variants for deterministic callers. Random and Shuffle are non-deterministic convenience filters; RandomWithRand and ShuffleWithRand accept explicit *rand.Rand values for deterministic callers.

Errors

Every public function returns *Error or wraps one. Errors are categorized by Kind: KindInvalidInput, KindNotFound, KindArithmetic, KindFormat. Match with errors.Is(err, ErrNotFound) (matches by Kind).

Stability

Stable semantics include UTF-8 length, UTC default timezone, nil/false-only falsiness, Find returning *Error{Kind:KindNotFound} on miss, Date's token grammar, and Map silently substituting nil for missing keys. See SPECS/00-runtime-contract.md for the durable runtime contract.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidInput error = kindError(KindInvalidInput)
	ErrNotFound     error = kindError(KindNotFound)
	ErrArithmetic   error = kindError(KindArithmetic)
	ErrFormat       error = kindError(KindFormat)
)

Sentinels classify errors by kind. Their dynamic value is immutable, so callers cannot corrupt process-wide errors.Is behavior.

Functions

func Abs

func Abs(input any) (float64, error)

Abs returns the absolute value of input.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result, _ := filter.Abs(-5)
	fmt.Println(result)
}
Output:
5

func Append

func Append(input, toAppend string) string

Append appends characters to the end of a string.

func AtLeast

func AtLeast(input, minimum any) (float64, error)

AtLeast returns max(input, minimum).

func AtMost

func AtMost(input, maximum any) (float64, error)

AtMost returns min(input, maximum).

func Average

func Average(input any) (float64, error)

Average returns the mean of numeric elements. Empty slice returns *Error{Kind:KindInvalidInput} (no defined mean).

func Base64Decode added in v0.4.15

func Base64Decode(input string) (string, error)

Base64Decode decodes a standard Base64 string.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result, _ := filter.Base64Decode("aGVsbG8gd29ybGQ=")
	fmt.Println(result)
}
Output:
hello world

func Base64Encode added in v0.4.15

func Base64Encode(input string) string

Base64Encode encodes a string with standard Base64 (RFC 4648).

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Base64Encode("hello world"))
}
Output:
aGVsbG8gd29ybGQ=

func Base64URLDecode added in v0.5.0

func Base64URLDecode(input string) (string, error)

Base64URLDecode decodes a URL-safe Base64 string.

func Base64URLEncode added in v0.5.0

func Base64URLEncode(input string) string

Base64URLEncode encodes a string with URL-safe Base64 (RFC 4648 §5).

func Bytes

func Bytes(input any) (string, error)

Bytes formats a non-negative whole-number byte count using SI/decimal units (e.g. 1024 → "1.0 KB", 1048576 → "1.0 MB"). Negative, fractional, non-finite, and overflowing inputs return *Error{Kind: KindInvalidInput}.

For binary (KiB / MiB) units, callers can compose humanize.BinaryBytes themselves; this helper owns only the SI form.

func Camelize

func Camelize(input string) string

Camelize converts input to camelCase.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Camelize("hello_world"))
	fmt.Println(filter.Camelize("foo-bar-baz"))
}
Output:
helloWorld
fooBarBaz

func Capitalize

func Capitalize(input string) string

Capitalize returns input with the first rune title-cased and the rest lowercased. It uppercases the first rune and lowercases the rest.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Capitalize("hELLO"))
	fmt.Println(filter.Capitalize("hello world"))
}
Output:
Hello
Hello world

func Ceil

func Ceil(input any) (float64, error)

Ceil rounds input up to the nearest whole number.

func Compact added in v0.4.15

func Compact(input any, key ...string) ([]any, error)

Compact removes nil elements. If key is provided, removes items where the property is nil or unreachable.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result, _ := filter.Compact([]any{"a", nil, "b", nil, "c"})
	fmt.Println(result)
}
Output:
[a b c]

func Concat added in v0.4.15

func Concat(input, other any) ([]any, error)

Concat returns a new slice containing the elements of input followed by the elements of other. Both must be slices or arrays.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result, _ := filter.Concat([]any{"a", "b"}, []any{"c", "d"})
	fmt.Println(result)
}
Output:
[a b c d]

func Dasherize

func Dasherize(input string) string

Dasherize converts input to lowercase words joined by dashes.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Dasherize("helloWorld"))
	fmt.Println(filter.Dasherize("FooBar"))
}
Output:
hello-world
foo-bar

func Date

func Date(input any, format string) (string, error)

Date formats input using this package's date format tokens. An empty format returns the canonical "2006-01-02 15:04:05" representation.

Supported tokens:

Y year (2024)            y year 2-digit (24)
m month 2-digit (03)     n month (3)
M month abbr (Mar)       F month full (March)
d day 2-digit (05)       j day (5)
D weekday abbr (Sat)     l weekday full (Saturday)
N ISO weekday 1-7        S ordinal suffix (st/nd/rd/th)
w weekday 0-6 (Sun=0)    z day of year 0-365
W ISO week (1-53)        o ISO week-numbering year
t days in month          L leap year flag (0/1)
H hour 24h 2-digit (07)  G hour 24h (7)
h hour 12h 2-digit (07)  g hour 12h (7)
i minute (07)            s second (07)
u microseconds           v milliseconds
A AM/PM uppercase        a am/pm lowercase
U Unix timestamp
O zone offset (+0800)    P zone offset (+08:00)
p P but UTC as Z         T zone abbreviation (UTC)
e zone identifier        I daylight-saving flag (0/1)
Z zone offset seconds    c ISO 8601 date
r RFC 2822 date          B Swatch Internet time

Unknown letters pass through as literals. A backslash escapes the next byte.

func Day

func Day(input any) (int, error)

Day returns the day of the month (1-31).

func Divide

func Divide(input, divisor any) (float64, error)

Divide divides input by divisor. Returns *Error{Kind: KindArithmetic} when divisor is zero.

func Escape added in v0.4.15

func Escape(input string) string

Escape escapes HTML special characters in input.

This is not an XSS defense; XSS protection requires the context-aware escaper in html/template.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Escape("<p>Hello & World</p>"))
}
Output:
&lt;p&gt;Hello &amp; World&lt;/p&gt;

func EscapeOnce added in v0.4.15

func EscapeOnce(input string) string

EscapeOnce escapes HTML special characters without double-escaping entities.

Same caveat as Escape: not an XSS defense.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.EscapeOnce("&lt;p&gt;already escaped&lt;/p&gt;"))
	fmt.Println(filter.EscapeOnce("1 < 2 & 3"))
}
Output:
&lt;p&gt;already escaped&lt;/p&gt;
1 &lt; 2 &amp; 3

func Extract

func Extract(input any, key string) (any, error)

Extract returns the value at key from input using dot-separated paths.

Keys can traverse maps, arrays, slices, structs, pointers, and interfaces. Failure modes:

  • nil input → *Error{Kind: KindInvalidInput}
  • empty key, missing path step, or out-of-range index → *Error{Kind: KindNotFound}
  • path step incompatible with the current value → *Error{Kind: KindInvalidInput}

Extract intentionally owns this tiny path language instead of outsourcing it to a broader query DSL. It is a core dynamic-value transformation.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	data := map[string]any{
		"user": map[string]any{
			"name": "Alice",
			"age":  30,
		},
	}
	name, _ := filter.Extract(data, "user.name")
	fmt.Println(name)
}
Output:
Alice

func Find added in v0.4.15

func Find(input any, key string, value any) (any, error)

Find returns the first item whose property at key equals value, or *Error{Kind: KindNotFound} if none matches.

func FindIndex added in v0.4.15

func FindIndex(input any, key string, value any) (int, error)

FindIndex returns the 0-based index of the first matching item, or -1.

func First

func First(input any) (any, error)

First returns the first element of a slice. Empty slices return *Error{Kind: KindNotFound}.

func Floor

func Floor(input any) (float64, error)

Floor rounds input down to the nearest whole number.

func Has added in v0.4.15

func Has(input any, key string, value any) (bool, error)

Has reports whether any item's property at key equals value.

func HasFunc added in v0.6.3

func HasFunc(input any, key string, predicate func(any) bool) (bool, error)

HasFunc reports whether any item's property at key satisfies predicate.

func Index

func Index(input any, i int) (any, error)

Index returns the element at i. Out-of-range returns *Error{Kind:KindNotFound}.

func Join

func Join(input any, separator string) (string, error)

Join concatenates the elements of input into a single string with separator between each element. Elements are stringified with fmt.Sprint.

An empty separator is allowed and equivalent to no separator.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result, _ := filter.Join([]string{"a", "b", "c"}, ", ")
	fmt.Println(result)
}
Output:
a, b, c

func Last

func Last(input any) (any, error)

Last returns the last element of a slice. Empty slices return *Error{Kind: KindNotFound}.

func Length

func Length(input string) int

Length returns the rune count of input. UTF-8 aware.

func Lower

func Lower(input string) string

Lower converts a string input to lowercase.

func Map

func Map(input any, key string) ([]any, error)

Map returns the values at key from each item in input. Items where the key is missing or unreachable contribute nil so the output preserves input cardinality.

func Max

func Max(input any) (float64, error)

Max returns the maximum numeric element.

func Min

func Min(input any) (float64, error)

Min returns the minimum numeric element.

func Minus

func Minus(input, subtrahend any) (float64, error)

Minus subtracts subtrahend from input.

func Modulo

func Modulo(input, modulus any) (float64, error)

Modulo returns the remainder of input divided by modulus. Returns *Error{Kind: KindArithmetic} when modulus is zero.

func Month

func Month(input any) (int, error)

Month returns the month number (1-12).

func MonthFull

func MonthFull(input any) (string, error)

MonthFull returns the full English month name (January..December).

func Number

func Number(input any, format string) (string, error)

Number formats input according to a `#,###.##`-style format string.

The format mirrors the convention historically used by `humanize.FormatFloat` in github.com/dustin/go-humanize so that templates such as `{{ value | number: '#,###.##' }}` keep producing identical output:

  • The number of `#` (or any character) after the `.` controls the decimal precision. Without `.`, integers render without decimals and non-integers keep their natural precision.
  • A `,` anywhere in the integer part inserts thousands separators.

Examples:

Number(1234567.89, "#,###.##") → "1,234,567.89"
Number(1234567,    "#,###.")    → "1,234,567"
Number(1234.5,     "#.#")        → "1234.5"
Number(1234,       "#")          → "1234"

Returns *Error{Kind: KindInvalidInput} for non-numeric input and *Error{Kind: KindFormat} for unparseable numeric strings.

func Ordinalize

func Ordinalize(number int) string

Ordinalize converts a numeric input to its ordinal English version.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Ordinalize(1))
	fmt.Println(filter.Ordinalize(2))
	fmt.Println(filter.Ordinalize(3))
	fmt.Println(filter.Ordinalize(11))
}
Output:
1st
2nd
3rd
11th

func Pascalize

func Pascalize(input string) string

Pascalize converts input to PascalCase.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Pascalize("hello_world"))
	fmt.Println(filter.Pascalize("foo-bar"))
}
Output:
HelloWorld
FooBar

func Pluralize

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

Pluralize selects the plural or singular form based on count.

It performs no string interpolation. Callers that need to embed the count must format it themselves (e.g. fmt.Sprintf("%d %s", n, Pluralize(n, "x", "xs"))).

When singular is empty it is derived from plural via inflection; when plural is empty it is derived from singular. English inflection is heuristic and best-effort.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Pluralize(1, "item", "items"))
	fmt.Println(filter.Pluralize(5, "item", "items"))
}
Output:
item
items

func Plus

func Plus(input, addend any) (float64, error)

Plus adds addend to input.

func Prepend

func Prepend(input, toPrepend string) string

Prepend prepends characters to the beginning of a string.

func Random

func Random(input any) (any, error)

Random returns one element chosen uniformly at random from input. Empty input returns *Error{Kind: KindNotFound}.

Random uses math/rand/v2's package-level generator. Call RandomWithRand when tests or callers need reproducible output.

func RandomWithRand added in v0.5.0

func RandomWithRand(r *rand.Rand, input any) (any, error)

RandomWithRand returns one element chosen by r. Passing nil returns *Error{Kind: KindInvalidInput}.

func Reject added in v0.4.15

func Reject(input any, key string, value any) ([]any, error)

Reject returns items whose property at key does not equal value.

func RejectFunc added in v0.6.3

func RejectFunc(input any, key string, predicate func(any) bool) ([]any, error)

RejectFunc returns items whose property at key does not satisfy predicate.

func Remove

func Remove(input, toRemove string) string

Remove removes all occurrences of a substring from a string.

func RemoveFirst added in v0.4.15

func RemoveFirst(input, toRemove string) string

RemoveFirst removes the first occurrence of a substring.

func RemoveLast added in v0.4.15

func RemoveLast(input, toRemove string) string

RemoveLast removes the last occurrence of a substring.

func Replace

func Replace(input, old, replacement string) string

Replace replaces all occurrences of a substring with another string.

func ReplaceFirst added in v0.4.15

func ReplaceFirst(input, old, replacement string) string

ReplaceFirst replaces the first occurrence of old with replacement.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.ReplaceFirst("hello hello hello", "hello", "hi"))
}
Output:
hi hello hello

func ReplaceLast added in v0.4.15

func ReplaceLast(input, old, replacement string) string

ReplaceLast replaces the last occurrence of old with replacement.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.ReplaceLast("hello hello hello", "hello", "hi"))
}
Output:
hello hello hi

func Reverse

func Reverse(input any) ([]any, error)

Reverse returns a new slice with elements in reverse order.

func Round

func Round(input, decimals any) (float64, error)

Round rounds input to the given number of decimal places.

decimals accepts any numeric type (int, float, or numeric string) so callers from template runtimes do not need to coerce first.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result, _ := filter.Round(3.14159, 2)
	fmt.Println(result)
}
Output:
3.14

func SeededRand added in v0.5.0

func SeededRand(s1, s2 uint64) *rand.Rand

SeededRand returns a deterministic *rand.Rand for callers that need reproducible RandomWithRand or ShuffleWithRand output.

r := filter.SeededRand(1, 2)
got, _ := filter.ShuffleWithRand(r, []int{1, 2, 3, 4})
// got is the same on every run.

The returned *rand.Rand follows math/rand/v2's usual rule: it is intended for one goroutine at a time. Use the package-level Random and Shuffle helpers when callers only need non-deterministic, concurrent-safe behavior.

func Shuffle

func Shuffle(input any) ([]any, error)

Shuffle returns a new slice with elements rearranged in random order. Shuffle uses math/rand/v2's package-level generator. Call ShuffleWithRand when tests or callers need reproducible output.

func ShuffleWithRand added in v0.5.0

func ShuffleWithRand(r *rand.Rand, input any) ([]any, error)

ShuffleWithRand returns a new slice with elements rearranged by r. Passing nil returns *Error{Kind: KindInvalidInput}.

func Size

func Size(input any) (int, error)

Size returns the length of a collection (slice, array, or map). Strings return their UTF-8 rune count, matching Length.

func Slice added in v0.4.15

func Slice(input any, offset int, length ...int) (any, error)

Slice extracts a substring or sub-slice. For strings the offset is in runes; for slices and arrays it is in elements. Negative offsets count from the end. length defaults to 1; out-of-range returns an empty result.

Inputs that are neither string nor slice/array return *Error{Kind: KindInvalidInput}.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	str, _ := filter.Slice("hello", 1, 3)
	fmt.Println(str)
	arr, _ := filter.Slice([]any{1, 2, 3, 4}, 1, 2)
	fmt.Println(arr)
}
Output:
ell
[2 3]

func Slugify

func Slugify(input string) string

Slugify converts input to a URL-friendly slug.

Note: Slugify is intentionally opinionated: transliteration and word boundary choices are policy, not universal truth.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result := filter.Slugify("Hello World!")
	fmt.Println(result)
}
Output:
hello-world

func Sort added in v0.4.15

func Sort(input any, key ...string) ([]any, error)

Sort sorts the slice in ascending order. If key is provided, items are sorted by that property. Numeric values use numeric comparison; otherwise values are compared as strings.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result, _ := filter.Sort([]any{"banana", "apple", "cherry"})
	fmt.Println(result)
}
Output:
[apple banana cherry]

func SortNatural added in v0.4.15

func SortNatural(input any, key ...string) ([]any, error)

SortNatural sorts case-insensitively. If key is provided, sorts by that property case-insensitively.

func Split

func Split(input, delimiter string) []string

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

func StripHTML added in v0.4.15

func StripHTML(input string) string

StripHTML removes tags, script blocks, style blocks, and comments from input on a best-effort basis.

This is not a sanitizer and not a security boundary. For untrusted HTML, use a real parser-based sanitizer (e.g. bluemonday). Provided here because it preserves the long-standing behavior of this package's StripHTML helper.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.StripHTML("<p>Hello <b>World</b></p>"))
}
Output:
Hello World

func StripNewlines added in v0.4.15

func StripNewlines(input string) string

StripNewlines removes newline characters from input.

func Sum

func Sum(input any) (float64, error)

Sum returns the sum of all numeric elements. Empty slice returns (0, nil).

func SumBy added in v0.5.0

func SumBy(input any, key string) (float64, error)

SumBy returns the sum of numeric values extracted at key from every element. Missing keys and non-numeric extracted values return errors.

func TimeAgo

func TimeAgo(input any) (string, error)

TimeAgo returns the difference between input and the current wall time in human-readable form ("3 hours ago", "in 5 minutes").

func TimeAgoWithClock added in v0.5.0

func TimeAgoWithClock(clock Clock, input any) (string, error)

TimeAgoWithClock returns the difference between input and clock.Now() in human-readable form. Tests should pass FixedClock for deterministic output.

func Times

func Times(input, multiplier any) (float64, error)

Times multiplies input by multiplier.

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.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result := filter.Trim("  hello  ")
	fmt.Println(result)
}
Output:
hello

func TrimLeft added in v0.4.15

func TrimLeft(input string) string

TrimLeft removes leading whitespace from input.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.TrimLeft("  hello  "))
}
Output:
hello

func TrimRight added in v0.4.15

func TrimRight(input string) string

TrimRight removes trailing whitespace from input.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.TrimRight("  hello  "))
}
Output:
hello

func Truncate

func Truncate(input string, maxLength int, ellipsis ...string) string

Truncate shortens input to maxLength runes. Default ellipsis is "...".

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Truncate("Hello, World!", 8))
	fmt.Println(filter.Truncate("Hi", 5))
	fmt.Println(filter.Truncate("Hello, World!", 10, "--"))
}
Output:
Hello...
Hi
Hello, W--

func TruncateWords

func TruncateWords(input string, maxWords int, ellipsis ...string) string

TruncateWords shortens input to maxWords words. Default ellipsis is "...".

func URLDecode added in v0.4.15

func URLDecode(input string) (string, error)

URLDecode decodes a percent-encoded string. Parse failure returns *Error{Kind: KindFormat}.

func URLEncode added in v0.4.15

func URLEncode(input string) string

URLEncode percent-encodes a string for use in a URL. Equivalent to url.QueryEscape.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.URLEncode("hello world"))
}
Output:
hello+world

func Unique

func Unique(input any) ([]any, error)

Unique removes duplicate elements while preserving first-seen order.

All elements must be Comparable. Non-comparable elements (slices, maps, functions, structs containing them) return *Error{Kind: KindInvalidInput} — use UniqueBy when records should be deduplicated by a property.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	result, _ := filter.Unique([]any{1, 2, 2, 3, 3, 3})
	fmt.Println(result)
}
Output:
[1 2 3]

func UniqueBy added in v0.5.0

func UniqueBy(input any, key string) ([]any, error)

UniqueBy removes duplicate elements by the value at key, preserving first-seen order. Missing or unreachable keys return an error.

func Upper

func Upper(input string) string

Upper converts a string input to uppercase.

func Week

func Week(input any) (int, error)

Week returns the ISO 8601 week-of-year (1-53).

func Weekday

func Weekday(input any) (string, error)

Weekday returns the full English weekday name (Sunday..Saturday).

func Where added in v0.4.15

func Where(input any, key string, value any) ([]any, error)

Where returns items whose property at key equals value.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	products := []any{
		map[string]any{"name": "Shoes", "available": true},
		map[string]any{"name": "Shirt", "available": false},
		map[string]any{"name": "Pants", "available": true},
	}
	result, _ := filter.Where(products, "available", true)
	for _, p := range result {
		m := p.(map[string]any)
		fmt.Println(m["name"])
	}
}
Output:
Shoes
Pants

func WhereFunc added in v0.6.3

func WhereFunc(input any, key string, predicate func(any) bool) ([]any, error)

WhereFunc returns items whose property at key satisfies predicate.

func Year

func Year(input any) (int, error)

Year returns the 4-digit year.

Types

type Clock added in v0.5.0

type Clock interface {
	Now() time.Time
}

Clock is the source of "now" for filters that depend on the current time.

Production code should use SystemClock{}; tests should inject a FixedClock to keep results deterministic.

type Error added in v0.5.0

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

Error is the only error type this package returns.

Callers use errors.As to extract it and switch on Kind. The four package-level sentinels (ErrInvalidInput, ErrNotFound, ErrArithmetic, ErrFormat) participate in errors.Is by Kind only — Op, Path, and Cause are diagnostic context, not part of identity.

func (*Error) Error added in v0.5.0

func (e *Error) Error() string

Error renders a stable message: "filter.<Op>: <kind>[: <path>][: <cause>]".

func (*Error) Is added in v0.5.0

func (e *Error) Is(target error) bool

Is reports whether target classifies the same kind.

func (*Error) Kind added in v0.5.0

func (e *Error) Kind() ErrorKind

Kind returns the stable error classification.

func (*Error) Op added in v0.5.0

func (e *Error) Op() string

Op returns the public operation that produced the error.

func (*Error) Path added in v0.5.0

func (e *Error) Path() string

Path returns the accessor path associated with the error, if any.

func (*Error) Unwrap added in v0.5.0

func (e *Error) Unwrap() error

Unwrap returns the underlying cause for use with errors.Is / errors.As.

type ErrorKind added in v0.5.0

type ErrorKind uint8

ErrorKind classifies failures returned by this package and its subpackages.

Kinds are deliberately coarse: four buckets cover every failure mode a pure value-transformation library can produce. Callers branch on Kind to map filter errors onto their own exit codes / HTTP status / log levels without maintaining a sentinel translation table.

const (
	// KindInvalidInput is returned when the caller passed a value of the
	// wrong type, the wrong shape, or out of range.
	KindInvalidInput ErrorKind = iota + 1
	// KindNotFound is returned when a path, key, or index does not exist
	// in the input.
	KindNotFound
	// KindArithmetic is returned for division by zero, modulus by zero,
	// and similar numeric-domain failures.
	KindArithmetic
	// KindFormat is returned when parsing fails (date layout, base64,
	// URL escape, etc.).
	KindFormat
)

func (ErrorKind) String added in v0.5.0

func (k ErrorKind) String() string

String returns a stable human-readable name for the kind.

type FixedClock added in v0.5.0

type FixedClock struct{ T time.Time }

FixedClock always returns the same instant. Use it in tests.

func (FixedClock) Now added in v0.5.0

func (c FixedClock) Now() time.Time

Now satisfies Clock.

type SystemClock added in v0.5.0

type SystemClock struct{}

SystemClock returns time.Now() in UTC.

func (SystemClock) Now added in v0.5.0

func (SystemClock) Now() time.Time

Now satisfies Clock.

Jump to

Keyboard shortcuts

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