Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. /// Converts numerical string vlaues with units into legit scss-> css values. No scientific notation numbers support yet ///
  2.  
  3. @function to-number($string) {
  4. /// Storing all legal data ///
  5. $numbers: ('0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9);
  6. $units: ('px': 1px, 'cm': 1cm, 'mm': 1mm, '%': 1%, 'ch': 1ch, 'pc': 1pc, 'in': 1in, 'em': 1em,
  7. 'rem': 1rem, 'pt': 1pt, 'ex': 1ex, 'vw': 1vw, 'vh': 1vh, 'vmin': 1vmin, 'vmax': 1vmax);
  8. /// Presetting vars ///
  9. $unit: 1;
  10. $minus: false;
  11. $divide: false;
  12. $result: 0;
  13. /// Parsing string by one char at a time ///
  14. @for $i from 1 through str-length($string) {
  15. $character: str-slice($string, $i, $i);
  16. $number: 0;
  17. /// Branching off wether its a number- OR other symbol- string ///
  18. @if map-has-key($numbers, $character) {
  19. $number: map-get($numbers, $character);
  20. } @else {
  21. /// Negative symbol, with decimals OR sth else ///
  22. @if $character == '-' {
  23. $minus: true;
  24. } @else if $character == '.' {
  25. $divide: 1;
  26. } @else {
  27. /// Either a unit of measure=located at the end with possibly more chars OR illegal char=warning ///
  28. $key: str-slice($string, $i);
  29. @if map-has-key($units, $key) {
  30. $unit: map-get($units, $key);
  31. } @else {
  32. @warn "Unknown character `#{$character}`. \
  33. -location string --> `#{$string}` \
  34. -index position --> `#{str-index($string, $character)}`";
  35. @return false;
  36. }
  37. }
  38. }
  39. /// Adding numbers moving to the left of '.' (2.0 -> 25.0 -> 257.0 -> ...) ///
  40. @if not $divide {
  41. $result: ($result * 10) + $number;
  42. } @else {
  43. /// On initial spotting of '.' we have to ignore the to-right-movement as we not yet add a number ///
  44. @if $character != '.' {
  45. /// Moving to the right of '.' (0.2 -> 0.25 -> 0.257 -> ...) ///
  46. $divide: $divide * 10;
  47. }
  48. /// Since we are past '.' and move to the right, we can only divide further when adding new numbers ///
  49. $result: $result + ($number / $divide);
  50. }
  51. }
  52. /// If true, negates the value, OR leaves it unchaged otherwise ///
  53. $result: if($minus, - $result, $result);
  54. /// At last applying units, default=1 OR from $units map ///
  55. @return ($result * $unit);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement