@use "sass:map";
@use "sass:math";

@function charsFromBase($base: 10) {
  $chars: (
    // Binary
    2: "01",
    // Octal
    8: "01234567",
    // Decimal
    10: "0123456789",
    // Hexadecimal
    16: "0123456789abcdef",
    // Base 36
    36: "0123456789abcdefghijklmnopqrstuvwxyz",
    // Base 64
    64: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  );

  @if not map.has-key($chars, $base) {
    @warn "There is no base `#{$base}` available.";
  }
  @return map.get($chars, $base);
}

@function is-negative($number) {
  @if type-of($number) == "number" {
    @return if($number < 0, true, false);
  } @else {
    @return false;
  }
}

// parseInt
// Parse a string to a number using a

@function parseInt($str, $radix: 10) {
  @if type-of($str) == "number" {
    @return $str;
  }
  $chars: charsFromBase($radix);
  $result: 0;

  $is-negative: is-negative($str);

  @for $i from 1 through str-length($str) {
    $char: str-slice($str, -$i, -$i);
    $value: str-index($chars, $char) - 1;
    $powed: math.pow($radix, ($i - 1));
    @if type-of($value) == "string" {
      @if $value == "-1" {
        $result: $result + ($powed * -1);
      }
    } @else {
      $result: $result + ($powed * $value);
    }
  }

  @return if($is-negative, -$result, $result);
}

// Half the value
@function half($num) {
  @return $num / 2;
}
@function h($num) {
  @return half($num);
}

// Make number ABS
@function abs($num) {
  @if $num >= 0 {
    @return $num;
  }
  @return -1 * $num;
}

// Make the number negative or positive
@function negative($num) {
  @if $num < 0 {
    @return abs($num);
  }
  @return parseInt($num);
}
@function n($num) {
  @return negative($num);
}

// A more simple function to create Percentages
@function perc($val, $of) {
  @return ($val / $of) * 100%;
}
