Last active
July 7, 2022 06:41
-
-
Save Danilo-Araujo-Silva/f006c53b4f6c5b833da628a03ca7df6c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/// https://css-tricks.com/snippets/sass/deep-getset-maps/ | |
/// Deep set function to set a value in nested maps | |
/// @author Hugo Giraudel | |
/// @access public | |
/// @param {Map} $map - Map | |
/// @param {List} $keys - Key chaine | |
/// @param {*} $value - Value to assign | |
/// @return {Map} | |
@function map-deep-set($map, $keys, $value) { | |
$maps: ($map,); | |
$result: null; | |
// If the last key is a map already | |
// Warn the user we will be overriding it with $value | |
@if type-of(nth($keys, -1)) == "map" { | |
@warn "The last key you specified is a map; it will be overrided with `#{$value}`."; | |
} | |
// If $keys is a single key | |
// Just merge and return | |
@if length($keys) == 1 { | |
@return map-merge($map, ($keys: $value)); | |
} | |
// Loop from the first to the second to last key from $keys | |
// Store the associated map to this key in the $maps list | |
// If the key doesn't exist, throw an error | |
@for $i from 1 through length($keys) - 1 { | |
$current-key: nth($keys, $i); | |
$current-map: nth($maps, -1); | |
$current-get: map-get($current-map, $current-key); | |
@if $current-get == null { | |
@error "Key `#{$key}` doesn't exist at current level in map."; | |
} | |
$maps: append($maps, $current-get); | |
} | |
// Loop from the last map to the first one | |
// Merge it with the previous one | |
@for $i from length($maps) through 1 { | |
$current-map: nth($maps, $i); | |
$current-key: nth($keys, $i); | |
$current-val: if($i == length($maps), $value, $result); | |
$result: map-merge($current-map, ($current-key: $current-val)); | |
} | |
// Return result | |
@return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same as the original code snippet from CSS tricks, this will always give an error related to
$key
variable not defined at line #33.