Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Sass `map-get()` return an error for a non-existent key?

Tags:

sass

node-sass

Why doesn't map-get() throw an error when the key does not exist in the supplied map?

For example:

$map: (
  'keyone': 'value',
  'keytwo': 'value',
  'keythree': 'value'
);

map-get($map, 'keyfour');

I'm aware of map-has-key() and I understand that might be useful on its own, but if I want to use map-get() smoothly, I shouldn't have to call map-has-key() each and every time. I'd expect the map-get() to throw an error, but instead it fails silently. Why is this not built into Sass?

If it matters, I'm using node-sass 3.2.0.

like image 986
Chris Montgomery Avatar asked Aug 11 '15 15:08

Chris Montgomery


1 Answers

The behavior of map-get() returning null rather than throwing an error when a key is not found in the mapping is by design. From the maintainer of Sass (on why nth() throws an error when requesting a missing element but map-get() does not):

In general, it's good to throw errors as early as possible when code is doing something wrong. It's very likely than an out-of-range list access is accidental and incorrect; by contrast, a missing key in a map is much more likely to be purposeful.

via https://github.com/sass/sass/issues/1721

I happen to disagree with nex3 on this (map-get() should throw an error, or at the very least throw a warning that can be suppressed). You can get your desired behavior by writing your own custom map-get function:

@function map-get-strict($map, $key) {
    @if map-has-key($map, $key) {
        @return map-get($map, $key);
    } @else {
        @error "ERROR: Specified index does not exist in the mapping";
    }   
}

$map:
  ( one: 1
  , two: 2
  );

.foo {
  test1: map-get-strict($map, one); // returns the expected value of `1`
  test2: map-get-strict($map, three); // raises an error
}
like image 132
cimmanon Avatar answered Oct 14 '22 06:10

cimmanon