/**
 * Copyright IBM Corp. 2020
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

// Map Extend
// jQuery-style extend function for when `map-merge()` isn't enough. Use when
// we need to merge more than two maps and/or need a merge to be recursive.
// @param $map
//   @type first map
// @param $maps
//   @type list of maps
// @param $deep
//   @type boolean
//   @default false
//   @desc Whether or not to enable recursive mode.
// @return merged map
@function map-extend($map, $maps... /*, $deep */) {
  $last: nth($maps, -1);
  $deep: $last == true;
  $max: if($deep, length($maps) - 1, length($maps));

  // Loop through all maps in $maps...
  @for $i from 1 through $max {
    // Store current map
    $current: nth($maps, $i);

    // If not in deep mode, simply merge current map with map
    @if not $deep {
      $map: map-merge($map, $current);
    } @else {
      // If in deep mode, loop through all tuples in current map
      @each $key, $value in $current {
        // If value is a nested map and same key from map is a nested map as well
        @if type-of($value) == 'map' and type-of(map-get($map, $key)) == 'map' {
          // Recursive extend
          $value: map-extend(map-get($map, $key), $value, true);
        }

        // Merge current tuple with map
        $map: map-merge(
          $map,
          (
            $key: $value,
          )
        );
      }
    }
  }

  @return $map;
}
