Last active
September 22, 2022 08:05
-
-
Save pascalduez/14ef79d644483fc262da to your computer and use it in GitHub Desktop.
Deep nested values in Sass maps
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
// ---- | |
// Sass (v3.3.7) | |
// Compass (v1.0.0.alpha.18) | |
// ---- | |
// Deep nested values in Sass maps. | |
// Fetch a deep value in a multi-level map. | |
// https://gist.github.com/KittyGiraudel/9933331 | |
@function map-fetch($map, $keys) { | |
@each $key in $keys { | |
$map: map-get($map, $key); | |
} | |
@return $map; | |
} | |
// Set or update a deep nested value in map. | |
@function map-set($map, $keys, $new) { | |
$orig: $map; | |
$cache: (); | |
$length: length($keys); | |
$last: nth($keys, $length); | |
@each $key in $keys { | |
$map: map-get($map, $key); | |
@if $key == $last { | |
$map: map-merge($map, $new); | |
} | |
$cache: append($cache, $map); | |
} | |
$i: $length; | |
@while $i > 1 { | |
$prev: $i - 1; | |
$cache: set-nth($cache, $prev, map-merge( | |
nth($cache, $prev), | |
(nth($keys, $i): nth($cache, $i)) | |
)); | |
$i: $prev; | |
} | |
@return map-merge($orig, (nth($keys, 1): nth($cache, 1))); | |
} | |
// Test | |
Sass { | |
$map: ( | |
one: ( | |
val: 1, | |
two: ( | |
val: 2, | |
three: ( | |
val: 3, | |
four: ( | |
val: 4 | |
) | |
) | |
) | |
), | |
foo: "foo", | |
bar: "bar" | |
); | |
$flag: "flag!"; | |
/* It should append a new value */ | |
$test: map-set($map, one two three four, (test: $flag)); | |
test: inspect($test); | |
test: map-fetch($test, one two three four test) == $flag; | |
/* It should update a defined value */ | |
$test: map-set($map, one two three four, (val: $flag)); | |
test: inspect($test); | |
test: map-fetch($test, one two three four val) == $flag; | |
} |
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
Sass { | |
/* It should append a new value */ | |
test: (one: ((val: 1, two: ((val: 2, three: ((val: 3, four: ((val: 4, test: "flag!")))))))), foo: "foo", bar: "bar"); | |
test: true; | |
/* It should update a defined value */ | |
test: (one: ((val: 1, two: ((val: 2, three: ((val: 3, four: ((val: "flag!")))))))), foo: "foo", bar: "bar"); | |
test: true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you - what a great little snippet 😄