0

I'm working on SASS unit-conversion function, and i have defined two functions:

convert-units(...);
strip-units(...);

Both work perfectly fine separately, until i pipe one in another, like this:

strip-units( convert-units(...) );

the result is following error:

invalid operands for multiplication on line 68 at column 23

I tried to copy manually result from convert-units() into strip-units(), and it it works correctly.

Here is the working example: http://sassmeister.com/gist/b5c61fc7baec1e3bec1f Please scroll to the bottom until you find commented pipe: strip-units(... fragment.

Any help would be appreciated.

Dariusz Sikorski
  • 4,309
  • 5
  • 27
  • 44

1 Answers1

0

This is because the line $pxValue / $size + $outputUnit actually does not create a number with a unit, but a string which looks exactly the same. There is no easy way to add a unit to a number in sass, but I found an answer in this question (there's also a little bit more background about why there is no easy way):

@function length($number, $unit) {
  $strings: 'px' 'cm' 'mm' '%' 'ch' 'pica' 'in' 'em' 'rem' 'pt' 'pc' 'ex' 'vw' 'vh' 'vmin' 'vmax';
  $units:   1px  1cm  1mm  1%  1ch  1pica  1in  1em  1rem  1pt  1pc  1ex  1vw  1vh  1vmin  1vmax;
  $index: index($strings, $unit);

  @if not $index {
    @warn "Unknown unit `#{$unit}`.";
    @return false;
  }

  @return $number * nth($units, $index);
}

Then simply do $outputValue: length($pxValue / $size, $outputUnit); and it works.

See my gist (I failed to make SassMeister save my updated code, don't know why)

Community
  • 1
  • 1
Markus
  • 5,667
  • 4
  • 48
  • 64
  • Amazing you dig into this question! I have found the same issue, `10 + px` is not the same as `10 * 1px`, i have modified my equations after that, and came with a simpler solution http://sassmeister.com/gist/c5aa6c3dbaf2aa0917ac but since i tested your answer and it's working too I can accept it :-) – Dariusz Sikorski Nov 20 '15 at 22:37
  • No Problem, and simpler is always better, that is for sure :-) – Markus Nov 20 '15 at 22:45
  • Ok, I have written some tests for unit conversions, and in some cases Your solution performs better, so I will keep with it. I think this may be useful in a part of a bigger tool I'm working on. Final version (probably) http://sassmeister.com/gist/026353b7d219c8e9b61a – Dariusz Sikorski Nov 20 '15 at 23:02