Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Converts numerical string vlaues with units into legit scss-> css values. No scientific notation numbers support yet ///
- @function to-number($string) {
- /// Storing all legal data ///
- $numbers: ('0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9);
- $units: ('px': 1px, 'cm': 1cm, 'mm': 1mm, '%': 1%, 'ch': 1ch, 'pc': 1pc, 'in': 1in, 'em': 1em,
- 'rem': 1rem, 'pt': 1pt, 'ex': 1ex, 'vw': 1vw, 'vh': 1vh, 'vmin': 1vmin, 'vmax': 1vmax);
- /// Presetting vars ///
- $unit: 1;
- $minus: false;
- $divide: false;
- $result: 0;
- /// Parsing string by one char at a time ///
- @for $i from 1 through str-length($string) {
- $character: str-slice($string, $i, $i);
- $number: 0;
- /// Branching off wether its a number- OR other symbol- string ///
- @if map-has-key($numbers, $character) {
- $number: map-get($numbers, $character);
- } @else {
- /// Negative symbol, with decimals OR sth else ///
- @if $character == '-' {
- $minus: true;
- } @else if $character == '.' {
- $divide: 1;
- } @else {
- /// Either a unit of measure=located at the end with possibly more chars OR illegal char=warning ///
- $key: str-slice($string, $i);
- @if map-has-key($units, $key) {
- $unit: map-get($units, $key);
- } @else {
- @warn "Unknown character `#{$character}`. \
- -location string --> `#{$string}` \
- -index position --> `#{str-index($string, $character)}`";
- @return false;
- }
- }
- }
- /// Adding numbers moving to the left of '.' (2.0 -> 25.0 -> 257.0 -> ...) ///
- @if not $divide {
- $result: ($result * 10) + $number;
- } @else {
- /// On initial spotting of '.' we have to ignore the to-right-movement as we not yet add a number ///
- @if $character != '.' {
- /// Moving to the right of '.' (0.2 -> 0.25 -> 0.257 -> ...) ///
- $divide: $divide * 10;
- }
- /// Since we are past '.' and move to the right, we can only divide further when adding new numbers ///
- $result: $result + ($number / $divide);
- }
- }
- /// If true, negates the value, OR leaves it unchaged otherwise ///
- $result: if($minus, - $result, $result);
- /// At last applying units, default=1 OR from $units map ///
- @return ($result * $unit);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement