@use "sass:list";

/**
* -- Replace list value at index --
*
* PARAMS
* - list: the list to edit
* - index: the position of the item you want to replace where the first item is indexed at 1
* - value: the new value you want to replace the value position at $index with
*/
@function replace-nth($list, $index, $value) {
  $result: null;

  @if type-of($index) != number {
    @warn "$index: #{quote($index)} is not a number for `replace-nth`.";
  } @else if $index == 0 {
    @warn "List index 0 must be a non-zero integer for `replace-nth`.";
  } @else if abs($index) > list.length($list) {
    @warn "List index is #{$index} but list is only #{list.length($list)} item long for `replace-nth`.";
  } @else {
    $result: (); // stylelint-disable-line scss/no-duplicate-dollar-variables
    $index: if($index < 0, list.length($list) + $index + 1, $index);

    @for $i from 1 through list.length($list) {
      @if $i == $index {
        $result: list.append($result, $value); // stylelint-disable-line scss/no-duplicate-dollar-variables
      } @else {
        $result: list.append($result, list.nth($list, $i)); // stylelint-disable-line scss/no-duplicate-dollar-variables
      }
    }
  }

  @return $result;
}
