Skip to content

Instantly share code, notes, and snippets.

@zellwk
Forked from pascalduez/SassMeister-input.scss
Created August 19, 2014 10:50
Show Gist options
  • Save zellwk/cd7d1eafe0debd9374fb to your computer and use it in GitHub Desktop.
Save zellwk/cd7d1eafe0debd9374fb to your computer and use it in GitHub Desktop.
scss: map-set by pascalduez
// ----
// 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/HugoGiraudel/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;
}
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