Skip to content

Instantly share code, notes, and snippets.

@alademann
Last active February 25, 2019 12:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alademann/ba3ff59ac7b9614e16dc to your computer and use it in GitHub Desktop.
Save alademann/ba3ff59ac7b9614e16dc to your computer and use it in GitHub Desktop.
Dot notation extension for SassyMap's map-get-deep Sass function
/**
* Fetch a deeply nested value in a multi-level map using object dot-notation string OR a list of keys.
*
* @requires sassy-maps
* @requires SassyLists
* @requires is-map
* @requires is-string
* @requires is-list
*
* @param {map} $map
* @param {string | list} $keys object dot-notation string representing the nesting order of the desired key
* @param {string} $delimiter string used to identify the individual keys within the string
*
* @throws if any of the `$required-functions` do not exist
* @throws if `$map` param is not a map
* @throws if `$keys` param is not a string or a list
*
* @return {*} value at nesting level requested via `$keys` param
*/
@function get($map, $keys, $delimiter: '.') {
$required-functions: is-map, is-string, is-list, sl-explode, map-get-deep;
@each $function in $required-functions {
@if not function-exists($function) {
@warn "`#{$function}()` is required by `get()`.";
@return null;
}
}
@if not is-map($map) {
@warn "`get` function expecting a map; #{type-of($map)} given.";
@return null;
}
@if not is-string($keys) and not is-list($keys) {
@warn "`get` function expecting a list or a string; #{type-of($keys)} given.";
@return null;
}
// END error-checking
@if is-list($keys) {
//
// its already a list, no need to split it
//
@return map-get-deep($map, $keys);
} @else {
@if not str-index($keys, $delimiter) {
//
// a single key has been requested - no recursion necessary
// (no `$delimiter` found in `$keys`)
//
@return map-get($map, $keys);
} @else {
//
// a `$delimiter` was found in the `$keys` string
// lets split it on the delimiter so we can pass a valid list of keys to `map-get-deep()`
//
$key-list: sl-explode($keys, $delimiter);
@return map-get-deep($map, $key-list)
}
}
}
@KittyGiraudel
Copy link

Since you are using SassyLists anyway, you could use the every function to do your initial check.

@if not every($required-functions, function-exists) {
  @warn "Missing dependencies.";
  @return null;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment