Packages

Glingify your strings!

Current section

Files

Jump to
gling src internal regexing.gleam
Raw

src/internal/regexing.gleam

import gleam/list
import gleam/option.{None, Some}
import gleam/regex.{type Match, Match}
import gleam/string
/// str is the String to be glingified.
/// re_str is the langauge specific String of regex which splits
/// all strings into a list of pairs of words and nonwords (in that order).
/// glingify_word_fn is a function which takes a word and returns it glingified.
pub fn glingify_by_regex(
str: String,
re_str: String,
glingify_word_fn: fn(String) -> String,
) -> String {
let assert Ok(re) = regex.from_string(re_str)
regex.scan(re, str)
|> list.fold(from: "", with: fn(str, m) {
let new_str = case m {
Match(_, [Some(word), Some(nonword)]) ->
string.append(glingify_word_fn(word), nonword)
Match(_, [Some(word), None]) -> glingify_word_fn(word)
Match(_, [None, Some(nonword)]) -> nonword
// For some reason javascript does [] instead of [None,None]
Match(_, [None, None]) | Match(_, []) -> ""
_ -> panic as "regex did not match exactly two groups"
}
string.append(str, new_str)
})
}