Skip to content

Instantly share code, notes, and snippets.

@Danilo-Araujo-Silva
Created March 13, 2017 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danilo-Araujo-Silva/be8bf59ece1ae16d5360c9029215b9fe to your computer and use it in GitHub Desktop.
Save Danilo-Araujo-Silva/be8bf59ece1ae16d5360c9029215b9fe to your computer and use it in GitHub Desktop.
/// jQuery-style extend function
/// About `map-merge()`:
/// * only takes 2 arguments
/// * is not recursive
/// @param {Map} $object - first map
/// @param {ArgList} $objects - other maps
/// @param {Bool} $deep - recursive mode
/// @return {Map}
@function extend($object, $objects.../*, $deep */) {
$last: nth($objects, -1);
$deep: $last == true;
$max: if($deep, length($objects) - 1, length($objects));
// Loop through all maps in $objects...
@for $i from 1 through $max {
// Store current map
$current: nth($objects, $i);
// If not in deep mode, simply merge current map with object
@if not $deep {
$object: map-merge($object, $current);
}
// If in deep mode
@else {
// Loop through all tuples in current map
@each $key, $value in $current {
// If value is a nested map and same key from object is a nested map as well
@if type-of($value) == "map" and type-of(map-get($object, $key)) == "map" {
// Recursive extend
$value: extend(map-get($object, $key), $value, true);
}
// Merge current tuple with object
$object: map-merge($object, ($key: $value));
}
}
}
@return $object;
}
// // Example
// // ---
// $map-1: (
// "first": "test",
// "second": "string",
// "third": (
// "nested": "gloubi",
// "map": 1337
// )
// );
// $map-2: (
// "first": 1,
// "second": ( "ohai": true ),
// "third": (
// "map": 42
// )
// );
// $map-3: (
// "new": "pwet",
// "third": (
// "are cool": 100
// )
// );
// test {
// extend-standard : inspect(extend($map-1, $map-2, $map-3));
// extend-recursive : inspect(extend($map-1, $map-2, $map-3, true));
// }
// test {
// extend-standard: ("first": 1, "second": (("ohai": true)), "third": (("are cool": 100)), "new": "pwet");
// extend-recursive: ("first": 1, "second": (("ohai": true)), "third": (("nested": "gloubi", "map": 42, "are cool": 100)), "new": "pwet");
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment