Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number from Sass map instead of string

Tags:

sass

mixins

I'm building a sass mixin where I make a calculation based on a value I get from a map. This is what I have this map:

$icons: (
  search: 1,
  arrow: 2,
  home: 3
);

And this mixin (simplified for this post):

@mixin addIcon($icon: 'arrow'){
  @if map-has-key($icons, $icon) {
     $posIcon: #{map-get($icons, $icon)};
     $posX: $posIcon * 48;
     @debug $posX;
  }
}

Now when I compile this I get an error because the value from the map is not a number but a string. So in this case the value 2 is a string. I found a way to change this to a number by using this:

@function number($value) {
  @if type-of($value) == 'number' {
    @return $value;
  } @else if type-of($value) != 'string' {
    $_: log('Value for `to-number` should be a number or a string.');
  }

  $result: 0;
  $digits: 0;
  $minus: str-slice($value, 1, 1) == '-';
  $numbers: ('0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9);

  @for $i from if($minus, 2, 1) through str-length($value) {
    $character: str-slice($value, $i, $i);

    @if not (index(map-keys($numbers), $character) or $character == '.') {
      @return to-length(if($minus, -$result, $result), str-slice($value, $i))
    }

    @if $character == '.' {
      $digits: 1;
    } @else if $digits == 0 {
      $result: $result * 10 + map-get($numbers, $character);
    } @else {
      $digits: $digits * 10;
      $result: $result + map-get($numbers, $character) / $digits;
    }
  }

  @return if($minus, -$result, $result);;
}

And then:

@mixin addIcon($icon: 'arrow'){
  @if map-has-key($icons, $icon) {
     $posIcon: #{map-get($icons, $icon)};
     $posX: number($posIcon) * 48;
     @debug $posX;
  }
}

But I have the feeling there must be a simpler way to do this. How can I make sure the value from the map is a number not a string?

like image 531
Zebda Avatar asked Nov 20 '25 15:11

Zebda


1 Answers

You get a string as value because you interpolate the result of map-get. If you remove the interpolation, you will get a number:

@mixin addIcon($icon: 'arrow'){
  @if map-has-key($icons, $icon) {
     $posIcon: map-get($icons, $icon);
     $posX: $posIcon * 48;
     @debug $posX;
  }
}
like image 193
Arkellys Avatar answered Nov 24 '25 22:11

Arkellys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!