mapx

May 31, 2026 ยท View on GitHub

sink-logo

mapx

mapx provides generic helpers for working with Go maps in a clear and reusable way.

It is designed to help you replace repetitive map loops with small functions for:

  • extracting keys and values
  • checking for key presence
  • transforming maps into other shapes
  • filtering and partitioning entries
  • combining, inverting, or counting entries

Overview

Use mapx when you want map logic to be easier to read, reuse, and test.

It is especially useful when:

  • the same map loop appears in multiple places
  • a helper makes the intent of the code clearer
  • you want type-safe generic utilities instead of custom one-off helpers

When to use it

Use mapx when:

  • you need a common map operation expressed clearly
  • you want to avoid repeating small loops throughout the codebase
  • you prefer reusable generic helpers over ad hoc implementations

Prefer a simpler local loop when:

  • the operation is tiny and only used once
  • a helper would make the code less obvious
  • performance or allocation behavior needs a specialized implementation

API reference

Extract keys or values

FunctionPurpose
KeysReturns all keys from a map
ValuesReturns all values from a map
UniqueValuesReturns only unique values from a map
SortedKeysReturns keys in ascending sorted order (ordered types only)
SortedKeysByFuncReturns keys sorted by a custom comparison function

Look up or check entries

FunctionPurpose
ContainsReturns true if the map contains all of the specified keys
ValueOrReturns the value for a key, or a fallback if the key is absent

Transform or reshape data

FunctionPurpose
ToSliceConverts a map into a slice using a mapper function
MapKeysReturns a new map with each key transformed by a mapper function
MapValuesReturns a new map with each value transformed by a mapper function
InvertSwaps map keys and values
CombineMerges multiple maps into one; last writer wins on key conflict
MergeMerges two maps into one using a resolver function to handle key conflicts

Filter, partition, or visit entries

FunctionPurpose
FilterReturns a map containing only entries that satisfy a predicate
AnyReturns true if any entry satisfies a predicate
AllReturns true if every entry satisfies a predicate; true for empty
PartitionSplits a map into two based on a predicate
CountReturns the number of entries whose value equals a candidate
CountByReturns a map of counts grouped by the result of a classifier
ApplyRuns a function on each map entry for side effects

Notes

  • Prefer the function that most clearly expresses your intent.
  • Prefer the simplest helper that matches the operation.
  • Map iteration order is not guaranteed; keep this in mind when ordering matters in your calling code.
  • Check each function's documentation for details such as key-conflict behavior and zero-value handling.

Examples