Moar
View SourceA dependency-free utility library containing 100+ useful functions. Add the library to your project, or just copy and paste the bits that you want.
- Repo: https://github.com/synchronal/moar
- Hex docs: https://hexdocs.pm/moar
This library is tested against the most recent 3 versions of Elixir and Erlang.
Sponsorship 💕
This library is part of the Synchronal suite of libraries and tools which includes more than 15 open source Elixir libraries as well as some Rust libraries and tools.
You can support our open source work by sponsoring us. If you have specific features in mind, bugs you'd like fixed, or new libraries you'd like to see, file an issue or contact us at contact@reflective.dev.
Installation
The package can be installed by adding moar to your list of dependencies in mix.exs:
def deps do
[
{:moar, "~> 4.1"}
]
endIf you'd rather not install the whole library, you can just copy some of its functions to your project.
Similar libraries
A quick tour
assert_containsasserts that a list or map contains one or more elements.assert_eqis a pipeable equality assertion, with options such as the ability to ignore order when comparing lists, ignore space when comparing strings, consider only certain keys of a map, returning a different value than what was passed in, and asserting that a value is within some delta (which can be a number or time duration).assert_recentasserts that a datetime is pretty close to now.assert_thatasserts that a pre-condition and post-condition are true after performing an action.refute_thatasserts that a condition didn't change after performing an action.
atomizewhen given an atom, returns it; when given a string, converts it to an atom, replacing non-alphanumeric characters with underscores.from_stringandto_stringconvert between strings and atoms, and don't fail if you try to convert an atom to an atom or a string to a string.to_existing_atomis likeString.to_existing_atom/1but can accept an atom as a param.
fetch_docs_as_markdownreturns a module's or function's docs as a markdown string
Moar.DateTime and Moar.NaiveDateTime
addandsubtractcan add and subtract aMoar.Duration, which is a tuple with a time unit, like{27, :minute}.atfor a duration on the current UTC day at the given time, optionally shifted by duration.between?determines whether a datetime is between two other datetimes.from_iso8601!raises if the string is not in ISO 8601 format.recent?returns true if the given datetime was at most one minute ago.to_iso8601_roundedconverts to an ISO 8601 string, truncated to the second.utc_nowtakesplusandminusoptions to get the current time plus or minus some duration.within?determines whether a given datetime is within the given duration.
- a protocol that defines
diff(a, b)along with implementations for datetimes.
- is a
{time, unit}tuple (like{27, :minute}) and supports the regularSystem.time_unit/0values and also:minute,:hour, and:day. agoreturns the duration between a given datetime and now.approxshifts the duration to a simple approximate value.betweenreturns the duration between two datetimes.convertconverts a duration to a new time unit, returning only the value.formatformats a duration in long ("3 seconds") or short ("3s") format with optional transformers and suffix.from_nowreturns a duration between now and a given datetime.humanizeconverts the duration to the highest possible time unit.shift,shift_up, andshift_downconvert a duration to a new time unit.to_stringrenders a duration into a string like"27 minutes".
at!is likeEnum.atbut raises if the index is out of bounds.compactrejects nil values.compact_blankrejects blank values as determined byMoar.Term.blank?/1.find_indicesreturns the indices of matching elementsfind_indices!returns the indices of matching elements and raises if any element is not found.first!returns the first item or raises if there isn't a first item.index_byconverts an enum into a list of maps indexed by the given function.into!is likeEnum.intobut allowsnilas its first argument.is_map_or_keywordreturns true if the value is a map or a keyword list (unfortunately cannot be used as a guard).isortandisort_bysort case-insensitively.lists_to_mapsconverts a list of lists to a lists of maps using the provided list of keys.take_atreturns a list of elements at the given indices.test_idsis liketids(see below) with a slightly different spelling.tidsextractstidfields. (tidis short for "test id" and the authors of Moar use tids extensively for testing.)
checksumreturns a sha256 checksum of a file.new_tempfile_pathreturns a new path for a tempfile, without creating it.stream!delegates toFile.stream!in a way that's compatible with older Elixir versions.write_tempfilewrites some data to a new tempfile.
cformatformats a string with ANSI codes;cstringandcputscreate and output those strings.
comparereturning:eq,:lt,:gt.
fillexpands (or shrinks) a list to a given size by repeating its elementsto_keywordconverts a list into a keyword list, using a default value or function to generate the valuesto_sentenceconverts a list into a string, with items separated by commas, and an "and" before the last itemunwrapreturns the argument if it's not a list, or returns the only item in the list, or raises.
atomize_key,atomize_keys, anddeep_atomize_keysconvert keys in a map from strings to atoms, whilestringify_keysanddeep_stringify_keysdo the opposite.compactremoves keys where the value is nil.compact_blankremoves keys where the value is blank.deep_taketakes a list of keys and{key, nested_key}tuples to take from nested maps.index_byconverts a list of maps into a map of maps indexed by the values of one of the keys.mergeanddeep_mergemerge maps, converting enumerables into maps before merging.deep_mergealso accepts a function to resolve value conflicts.merge_if_blankmerge maps, retaining existing non-blank values.put_if_blankputs a key/value pair into a map if the key is missing or its value is blank (viaMoar.Term.blank?/1)put_new!is likeMap.put_new/3but raises if the key already exists in the map.rename_keyandrename_keysrename keys in a map.transformtransforms a key or multiple keys with a transformer function.validate_keys!validates that the keys in the map are equal to or a subset of a list of valid keys.
- is meant to be used with function options.
deletedeletes a value from opts.getextracts a value from opts, falling back to a default if the value is blank (viaMoar.Term.blank?/1)popremoves a value from opts, falling back to a default if the value is blank (viaMoar.Term.blank?/1)takeextracts multiple values from opts, falling back to defaults if the value is blank (viaMoar.Term.blank?/1)
implements!raises if a struct does not implement the given protocol.implements?returns true if a struct implements the given protocol.
dom_idreturns a random string that is a valid DOM ID, with an optional prefix.floatreturns a random float.fuzzincreases or decreases a number by a random percent.integerreturns a random integer.stringreturns random base64- or base32-encoded string.
named_capturegets a single named capture.named_capturesis likeRegex.named_captures/3but can take the first two args in any order.
rescue_untilandrescue_forrun the given function repeatedly until it does not raise.retry_untilandretry_forrun the given function repeatedly until it returns a truthy value.
append_unless_blankappends a suffix to a string, unless the string is blank.compareandcompare?compare two strings, optionally transforming the strings before comparison.count_leading_spaces/1returns the number of leading spaces in a string.inner_truncateremoves the middle of a string to make it the desired length.joinjoins multiple items, as a shortcut toEnum.map_join([item1, item2, ...], "-", &to_string/1)loremgenerates a "lorem ipsum" string of the given length.quotesurrounds the given string with quotation marks (with various quote styles supported).remove_marked_whitespaceremoves whitespacing following a special\vmarker.secure_comparecompares two strings in constant time.slugconverts a string into a slug with a custom joiner character;dasherizeandunderscoreare shortcuts for common slug formats.squishcollapses consecutive whitespace characters.surroundwraps a string with the given characters.to_caseconverts text to:camel_case,:kebab_case,:lower_camel_case, or:snake_case.to_integerconverts a string to an integer with a few handy options.trimis likeString.trim/1but handlesnilvalues.truncate_attruncates a string at the last instance of a substring that results in the truncated string being shorter than a given length.unindent/1un-indents a multiline string by the smallest indentation size.unindent/2un-indents a multiline string by the given amount.
cont,error,halt,ok, andnoreplycreate tuples ("foo" |> error()->{:error, "foo"}).replycreates a tuple ({:reply, message, state}).cont!,error!,halt!,ok!, andnoreply!unwrap tuples ({:error, "foo"} |> error!()->"foo").returningtakes two arguments and returns the second one.then_iffor piping a term into a function only if a condition is truthy.
blank?returns true if a term isnil, an empty string, a whitespace-only string, an empty list, or an empty map.present?is the opposite ofblank?.presencereturns a default if the argument is blank.
from_list!converts a list of tuples like[{:ok, 1}, {:ok, 2}, {:ok, 3}]to a tuple like{:ok, [1, 2, 3]}reduceconverts a list of tuples like[{:ok, 1}, {:error, 2}]to a map like%{ok: [1], error: [2]}
fixapplies some fixes to a URI string.formatformats a URI in various ways.valid?returns true if the URI has a host and scheme, and if it has a path, the path does not contain spaces; it also supportsmailtoURIs.web_url?returns true if the scheme ishttporhttps.
regexreturns a Regex that matches valid UUIDs.valid?returns true if the given string is a valid UUID.
compareis likeVersion.compare/2but normalizes the versions first.normalizeappends as many ".0" strings as necessary to create a string with major, minor, and patch numbers.