map.key-replace()

The map.key-replace() function returns the map with key $replace replaced by $replacement.

// Sass.
@use 'sass:map';

// Functions.
@use '../string';

// The `map.key-replace()` function.
@function key-replace($map, $replace, $replacement) {
  @if type-of($map) == map {
    @each $key, $value in $map {
      $map: map.remove($map, $key);
      @if type-of($key) ==
        string and
        type-of($replace) ==
        string and
        type-of($replacement) ==
        string
      {
        @if string.index($key, $replace) {
          $key: string.replace($key, first, $replace, $replacement);
        }
      } @else if $key == $replace {
        $key: $replacement;
      }

      $map: map.merge(
        $map,
        (
          $key: $value,
        )
      );
    }
  }
  @return $map;
}

Parameters

$map

A map in which a $replace key is replaced with $replacement.

$replace

A key, or if string substring to replace with $replacement in $map.

$replacement

The value to replace a $replace key in $map.

Return

The return value is a $map with replaced key $replace by $replacement.

Examples

// Use.
@use '@angular-package/sass/map';

// Examples.
$-map: (
  key replace: (map: 1),
  key-replace: (map: 2),
);

// replace string key
@debug map.key-replace($-map, key-replace, new-key); // (key replace: (map: 1), new-key: (map: 2))
@debug map.key-replace(('bold king': 1, b: 2, c: 3), 'bold', 'hairy'); // ("hairy king": 1, b: 2, c: 3)
@debug map.key-replace(('bold king': 1, b: 2, c: 3), 'o', 'ooo'); // ("booold king": 1, b: 2, c: 3)
@debug map.key-replace((a: 1, b: 2, c: 3), 'a', 'd'); // (d: 1, b: 2, c: 3)

// replace string key with a list key
@debug map.key-replace($-map, key-replace, new key); // (key replace: (map: 1), new key: (map: 2))

// replace list key
@debug map.key-replace($-map, key replace, 'd'); // (d: 1, b: 2, c: 3)

Last updated