Localize.Utils.String (Localize v0.32.0)

Copy Markdown View Source

String manipulation functions not provided in the standard library.

Provides utilities for hashing strings, converting between naming conventions (camelCase to snake_case), and character case conversion.

Summary

Functions

Hashes a string using a polynomial rolling hash function.

Converts a single character to its lowercase equivalent.

Replaces hyphens with underscores in a string.

Converts a single character to its uppercase equivalent.

Converts a CamelCase or PascalCase string or atom to snake_case.

Functions

hash(string)

@spec hash(String.t()) :: non_neg_integer()

Hashes a string using a polynomial rolling hash function.

See https://cp-algorithms.com/string/string-hashing.html for a description of the algorithm.

Arguments

  • string — the string to hash.

Returns

  • A non-negative integer hash value.

Examples

iex> Localize.Utils.String.hash("hello")
61_454_117

to_lower_char(char)

@spec to_lower_char(integer()) :: integer()

Converts a single character to its lowercase equivalent.

Only operates on ASCII uppercase letters (A-Z).

Arguments

  • char — an integer codepoint.

Returns

  • The lowercase codepoint if the input is an uppercase ASCII letter, otherwise the input unchanged.

to_underscore(string)

@spec to_underscore(String.t()) :: String.t()

Replaces hyphens with underscores in a string.

Arguments

  • string — the string to transform.

Returns

  • A new string with all "-" characters replaced by "_".

Examples

iex> Localize.Utils.String.to_underscore("this-one")
"this_one"

to_upper_char(char)

@spec to_upper_char(integer()) :: integer()

Converts a single character to its uppercase equivalent.

Only operates on ASCII lowercase letters (a-z).

Arguments

  • char — an integer codepoint.

Returns

  • The uppercase codepoint if the input is a lowercase ASCII letter, otherwise the input unchanged.

underscore(atom)

@spec underscore(atom() | String.t()) :: String.t()

Converts a CamelCase or PascalCase string or atom to snake_case.

This is a modified version of Macro.underscore/1 that correctly handles strings containing underscores between capitalized words (e.g., "This_That" becomes "this_that" instead of "this__that").

Arguments

  • value — an atom or string to convert.

Returns

  • A snake_case string.

Examples

iex> Localize.Utils.String.underscore("HelloWorld")
"hello_world"

iex> Localize.Utils.String.underscore("This_That")
"this_that"