Created
March 13, 2017 18:57
-
-
Save Danilo-Araujo-Silva/be8bf59ece1ae16d5360c9029215b9fe to your computer and use it in GitHub Desktop.
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
/// 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