@use "sass:math";

@import "tools.getBaseFontSize";

$base-font-size: get-base-font-size();

@function rem($pxValue) {
  $value: #{math.div(strip-unit-if-present($pxValue), strip-unit-if-present($base-font-size))};

  @return cast-to-number($value) * 1rem;
}

@function strip-unit-if-present($value) {
  @if type-of($value) == "number" and str-index($value + "", "px") == null {
    @return $value;
  } @else {
    $strippedValue: math.div($value, 1px);

    @return $strippedValue;
  }
}

@function cast-to-number($value) {
  @if type-of($value) == "number" {
    @return $value;
  } @else if type-of($value) != "string" {
    @error 'The parameter "#{$value}" should be of type "number" or "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 $character == "." {
      $digits: 1;
    } @else if $digits == 0 {
      $result: $result * 10 + map-get($numbers, $character);
    } @else {
      $digits: $digits * 10;
      $result: $result + math.div(map-get($numbers, $character), $digits);
    }
  }

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