Search code examples
csssasshexstring-conversion

How to convert integer to hex in SASS


In lieu of something like the Map data structure that Chris Eppstein mentions as a work in progress for SASS, I'm trying to achieve something similar - mapping a string to a corresponding hex value, which will be used to specify a unicode character for CSS content property. (I'm trying to refactor some font icon SASS code.)

At the moment I have something rudimentary like:

/*icon1  -->  \F000
  icon2  -->  \F001
  icon3  -->  \F002*/

@function u-char($name) {
    @if $name == icon1 {
        @return "000";
    } @else if $name == icon2 {
        @return "001";
    } @else if $name == icon3 {
        @return "001";
    }
}

@mixin icon-class($name) {
    ...
    content: "\f#{u-char($name)}";
    ...
}

But I'm actually trying to map a large number of characters, so this approach is arduous. I was hoping to be able to do something like:

@function u-char($name) {
    $i: 0;
    $itemList: item1, item2, item3;

    @each $currItem in $itemList {
        @if $name == item1 {
            @return i-to-hex-str($i);
        }
        $i: $i + 1;
    }
}

Is there anything that does and integer to hex string conversion in SASS? Is there another elegant way around this?


Solution

  • I would do this:

    $icons: "000", "001", "002";
    
    @function icon($i) {
      @return "\F#{nth($icons, 1)}";
    }
    
    h1::before {
      content: icon(1);
    }
    

    Edit:

    If you want to associate a word with a value, try using a list of lists and iterating through them. I'm not going to pretend this is very efficient, but it works. It would be nice if Sass had hashes.

    $icons: '000' calendar, '001' inbox, '002' home
    
    @function icon($call)
      @for $i from 1 through length($icons)
        @if $call == nth(nth($icons, $i), 2)
          @return "\F#{nth(nth($icons, $i), 1)}"
    
    h1::before
      content: icon(calendar)