// =============================================================================
// =ALEKSI - MAP-REPLACE-NTH
// =============================================================================
////
//// @group aleksi-maps
//// @author [Yoannis Jamar](https://yoannis.com)

@import "aleksi/general/throw";

// =map-replace-nth( $map, $index, $val )
// -----------------------------------------------------------------------------
/// Replaces the nth entry from a map with given tuple.
///
/// @param {map} $map - The map from which to remove the tuple
/// @param {number} $index - The index of the tuple to remove
///
/// @return {map} - The map with $val insteaf of the tuple that was at $index
///
/// @throw Error if `$map` is not a map
/// @throw Error if `$index` is out of bounds for $map
/// @throw Error if `$tuple` is not a tuple (e.g. map with a single item)
///
/// @example scss
///   $foo: map-replace-nth(('a': 'foo', 'b': 'bar'), 2, ('b': 'wiz'));
///     // => ('a': 'foo', 'b': 'wiz')
///   $foo: map-replace-nth(('a': 'foo', 'b': 'bar'), 3, ('b': 'wiz'));
///     // => null (Error)
///
/// @access public
/// @since 0.4.0

@function map-replace-nth($map, $index, $tuple)
{
  @if type-of($map) != 'map' {
    @return throw-error('map-replace-nth(): $map must be a map – was #{inspect($map)}');
  }

  @if type-of($index) != 'number' {
    @return throw-error('map-replace-nth(): $index must be a number – was #{inspect($index)}');
  }

  @if $index > length($map) {
    @return throw-error('map-replace-nth(): index #{$index} out of bounds for #{inspect($map)}.');
  }

  @if type-of($tuple) != 'map' or length($tuple) != 1 {
    @return throw-error('map-replace-nth(): $val must be a tuple – was #{inspect($val)}');
  }

  $res: ();
  $i: 0;

  @each $key, $val in $map
  {
    $i: $i + 1;
  
    @if $i == $index {
      $key: nth(map-keys($tuple), 1);
      $val: nth(map-values($tuple), 1);
    }

    $res: map-merge($res, ('#{$key}': $val));
  }

  @return $res;
}