From 3293e6fe59141e4322cf56aacfa4a67a5b5dc58c Mon Sep 17 00:00:00 2001 From: Volpeon Date: Mon, 24 Jun 2024 16:43:38 +0200 Subject: Add to-number and to-length --- src/_functions.scss | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/src/_functions.scss b/src/_functions.scss index 7d4a695..8a1a613 100644 --- a/src/_functions.scss +++ b/src/_functions.scss @@ -16,6 +16,26 @@ @use 'sass:meta'; @use './vars'; +$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 +); + /// /// Replace a substring with a new string. /// @@ -290,6 +310,61 @@ @return math.div($size, $base) * 1rem; } +/// +/// Casts a string into a number +/// +/// @param {string|number} $value +/// +/// @return {number} +/// +@function to-number($value) { + @if meta.type-of($value) == 'number' { + @return $value; + } + @if meta.type-of($value) != 'string' { + @error 'Value for `to-number` should be a number or a string.'; + } + + $result: 0; + $digits: 0; + $minus: string.slice($value, 1, 1) == '-'; + + @for $i from if($minus, 2, 1) through string.length($value) { + $character: string.slice($value, $i, $i); + + @if not list.index(map.keys($numbers), $character) or $character == '.' { + @return to-length(if($minus, -$result, $result), string.slice($value, $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); +} + +/// +/// Add $unit to $value +/// +/// @param {number} $value - Value to add unit to +/// @param {string} $unit - String representation of the unit +/// +/// @return {number} $value expressed in $unit +/// +@function to-length($value, $unit) { + @if not list.index(map.keys($units), $unit) { + @error 'Invalid unit `#{$unit}`.'; + } + + @return $value * map.get($units, $unit); + } + /// /// A mixin with the sole purpose of letting you use temporary variables without polluting the global namespace. /// -- cgit v1.2.3-70-g09d2