Last active
February 25, 2019 12:40
-
-
Save alademann/ba3ff59ac7b9614e16dc to your computer and use it in GitHub Desktop.
Dot notation extension for SassyMap's map-get-deep Sass function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since you are using SassyLists anyway, you could use the
every
function to do your initial check.