filter

package module
v0.4.16 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 23 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 input is nil, false, or empty string.
Trim Removes leading and trailing whitespace.
TrimLeft Removes leading whitespace (Liquid lstrip).
TrimRight Removes trailing whitespace (Liquid rstrip).
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.

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.
Index Returns the element at a specified index.
Random Selects a random element from the slice.
Reverse Reverses the order of elements.
Shuffle Randomly rearranges the elements.
Size Determines the size of a slice, array, or map.
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.
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.
Reject Filters removing elements matching a property value.
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.

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 transforming data in template rendering pipelines. It supports:

  • String manipulation: case conversion, truncation, slugification
  • Array operations: unique, sort, shuffle, aggregation
  • Date formatting: date parsing, component extraction, relative time
  • Number formatting: numeric formatting, byte humanization
  • Math operations: arithmetic, rounding, clamping

All functions accept interface{} inputs for maximum flexibility in dynamic template contexts.

Index

Examples

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")
	// ErrNegativeValue indicates the input must be non-negative
	ErrNegativeValue = errors.New("input must be non-negative")
)

Functions

func Abs

func Abs(input any) (float64, error)

Abs returns the absolute value of the 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 the larger of input and minimum.

func AtMost

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

AtMost returns the smaller of input and maximum.

func Average

func Average(input any) (float64, error)

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

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 to standard Base64.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

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

func Bytes

func Bytes(input any) (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. It lowercases the first letter of the first segment and capitalizes the first letter of each subsequent segment.

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 capitalizes the first letter and lowercases the rest. This matches Liquid's capitalize behavior.

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 the 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 from a slice. If key is provided, removes elements where the property is nil.

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 combines two slices into one.

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 a string to a lowercased, dashed string, removing non-alphanumeric characters.

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 a timestamp into a specified format. Returns a string representation of the date.

func Day

func Day(input any) (int, error)

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

func Default

func Default(input, defaultValue any) any

Default returns defaultValue if input is nil, false, or empty string.

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

func main() {
	fmt.Println(filter.Default("", "fallback"))
	fmt.Println(filter.Default("value", "fallback"))
	fmt.Println(filter.Default(nil, "fallback"))
	fmt.Println(filter.Default(false, "fallback"))
}
Output:
fallback
value
fallback
fallback

func Divide

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

Divide divides the first value by the second.

func Escape added in v0.4.15

func Escape(input string) string

Escape converts <, >, &, ", ' to HTML entities.

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 converts <, >, &, ", ' to HTML entities without double-escaping. Already escaped entities like &amp; &lt; &#39; are preserved.

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

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 element in a slice where the given property equals the given value.

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 element where the given property equals the given value. Returns -1 if not found.

func First

func First(input any) (any, error)

First returns the first element of a slice.

func Floor

func Floor(input any) (float64, error)

Floor rounds the 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 returns true if any element in the slice has a property matching the given criteria. If value is provided, checks property == value. If value is omitted, checks property is truthy.

func Index

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

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

func Join

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

Join joins the elements of a slice into a single string with a given 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.

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 any, key string) ([]any, 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 any) (float64, error)

Max returns the maximum value from a slice of float64.

func Min

func Min(input any) (float64, error)

Min returns the minimum value from a slice of float64.

func Minus

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

Minus subtracts the second value from the first.

func Modulo

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

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

func Month

func Month(input any) (int, error)

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

func MonthFull

func MonthFull(input any) (string, error)

MonthFull returns the full month name from the input date.

func Number

func Number(input any, 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.

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 a string to PascalCase, capitalizing the first letter of each segment.

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 returns the singular or plural form of a string based on count. If the form string contains "%d", the count is substituted into the result. Otherwise, only the appropriate form string is returned without the count.

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 two numbers.

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 selects a random element from a slice.

func Reject added in v0.4.15

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

Reject filters a slice, removing elements where the given property equals the given value. If value is omitted, removes elements where the property is truthy. Inverse of Where.

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 in the input 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 reverses the order of elements in a slice.

func Round

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

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

Example
package main

import (
	"fmt"

	"github.com/kaptinlin/filter"
)

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

func Shuffle

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

Shuffle randomly rearranges the elements of the slice.

func Size

func Size(input any) (int, error)

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

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: returns substring starting at offset with optional length. For slices: returns sub-slice starting at offset with optional length. Negative offset counts from end (-1 = last element). If length is omitted, returns single character/element.

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.

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 a slice in ascending order. If key is provided, sorts slice of maps/structs by that property. Elements whose key cannot be extracted retain their relative order.

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 a slice case-insensitively. If key is provided, sorts by that property case-insensitively. Elements whose key cannot be extracted retain their relative order.

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 all HTML tags, script blocks, style blocks, and comments from the input.

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 all newline characters (\n, \r\n, \r) from the input.

func Sum

func Sum(input any) (float64, error)

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

func TimeAgo

func TimeAgo(input any) (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, multiplier any) (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.

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 a string. Liquid equivalent: lstrip.

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 a string. Liquid equivalent: rstrip.

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 truncates a string to maxLength characters (including ellipsis). An optional ellipsis string can be provided (default "...").

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 truncates a string to a specified number of words. An optional ellipsis string can be provided (default "...").

func URLDecode added in v0.4.15

func URLDecode(input string) (string, error)

URLDecode decodes a percent-encoded string.

func URLEncode added in v0.4.15

func URLEncode(input string) string

URLEncode percent-encodes a string for use in URLs.

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 from a slice. It uses a comparable map for comparable types (fast path) and falls back to hash-based deduplication for non-comparable types like slices and maps.

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 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 week number from the input date.

func Weekday

func Weekday(input any) (string, error)

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

func Where added in v0.4.15

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

Where filters a slice, keeping elements where the given property equals the given value. If value is omitted, keeps elements where the property is truthy.

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 Year

func Year(input any) (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