4

The following code will create an empty map in the variable $test, but is there a proper way to accomplish the this? This seems too hackish to be the best way to get an empty map.

$test: map-remove((default:null), 'default');

@if type-of($test) != map {
    @warn "This is not a map: #{inspect($test)}";
}
@else {
    @warn "This is a map: #{inspect($test)}";
}

WARNING: This is a map: ()
         on line 7 of app/styles/functions/map.scss
roydukkey
  • 3,149
  • 2
  • 27
  • 43

2 Answers2

2

Empty maps can be created in a very simple way:

$emptyMap: ();

According to the official documentation on maps, empty lists and maps are both created using just (). So the above code is a perfectly valid empty map, but when testing the type, the console will tell you it's a list (note that its type is still either map or list).

$map: ();
@warn "#{type-of($map)}";
// Warning: list

Once you add something to the map, the console will tell you it's a map.

$map: ();
$newMap: map-merge($map, (1: test));
@warn "#{type-of($newMap)}";
// Warning: map
Adam
  • 3,829
  • 1
  • 21
  • 31
  • I understand. I don't intent to add anything to it, but I do intent to pass it through `map-has-key()`, and this is a problem if the type is `list`. – roydukkey Sep 28 '18 at 18:09
  • Even though the console reports an empty map as a list, it is still considered either an empty map or empty list. You can pass it through `map-has-key()` just fine. – Adam Sep 28 '18 at 18:13
  • Humm... Yes, seems so. I swear I was getting a error with it earlier. – roydukkey Sep 28 '18 at 18:25
  • If this solution works for you, please accept it as the correct answer. – Adam Oct 25 '18 at 07:32
1

There is no better native way to do that, but you could make it shorter.

$map: map-remove((x:x), x);

.foo {
  output: type-of($map); // map
}

Another solution would be to use a custom function.

@function empty-map($x: x) {
  @return map-remove(($x:$x), $x);
}

$map2: empty-map();
$map3: empty-map();

.foo {
  output: type-of($map2); // map
  output: type-of($map3); // map
}

SassMeister demo

Quentin Veron
  • 3,079
  • 1
  • 14
  • 32