sassscss-mixins

Simple scss map generated by for loop


I want to have a map like this:

$spacers: (
   0: 0,
   1: 4px,
   2: 8px,
   etc.
);

This is my code:

$spacer: 4px;

$spacers: ();

@function map-set($map, $key, $value) {
  $new: ($key: $value);
  @return map-merge($map, $new);
}

@for $i from -5 through 12 {
  map-set($spacers, $i, $i * $spacer);
}

Yet I'm thrown an error

enter image description here

I tried different variations, adding the loop inside a function, etc., but I get the same error...


Solution

  • You have to set the values of $spacers to the return value of map-set. I am also assuming map-merge is another function you wrote, otherwise just use the built in map.merge method and add @use "sass:map" to the top of your file.

    $spacer: 4px;
    $spacers: ();
    
    @function map-set($map, $key, $value) {
      $new: ($key: $value);
      @return map-merge($map, $new);
    }
    
    @for $i from -5 through 12 {
      $spacers: map-set($spacers, $i, $i * $spacer);
    }
    

    You could also just write the following (although I do not know your use case so please ignore if this isn't useful):

    @use "sass:map";
    
    $spacer: 4px;
    $spacers: ();
    
    @for $i from -5 through 12 {
      $spacers: map.set($spacers, $i, $i * $spacer);
    }