Posts /

SASS reversed string

  • SASS
07 JUL 2015

Lately I was having a look at some quiz test with some friends. The answer always started like this: "How would you do that with ruby" or "How would you do that with Javascript". Since SASS comes with some advanced functions I could participate into some of them and be proud that even a preprocessor like SASS can stole some glory of these programming languages.

These tests are just for fun without any real usage I could think of. so let's start

Reverse a string

The question was: "How would you reverse a string like 'this is awesome' in SASS"

Look at following solution

          
            @function str-reverse($string) {
              $reverse-string: "";

              @for $i from 1 through str-length($string) {
                $c: str-slice($string, $i, $i);
                $reverse-string: "#{$c}#{$reverse-string}";
              }

              @return $reverse-string;
            }
          
        

So how this work? Let's a have a look at each sass functions.

First of all we need to create an empty variable to hold our reversed string. Then we create a loop for each character our strings contains. To achieve this we use the power of str-length.

An example:

          
            str-lenght("foo") // = 3
            str-lenght("awesome") // = 7
            str-lenght("this is awesome") // = 15
          
        

So our loop contain 15 steps from 1 to 15. Then we need to slice our string and pick each letter. We used the str-slice to achieve this.

An example:

          
            str-slice("foo", 1, 1) // = f
            str-slice("awesome", 1, 1) // = a
            str-slice("this is awesome",1 ,1) // = t
          
        

str-slice($string, $start-at, [$end-at]) // Extracts a substring from $string.

An example:

          
            str-slice("foo", 1, 2) // = fo
            str-slice("awesome", 2, 4) // = wes
            str-slice("this is awesome",4 ,9) // = s is a
          
        

For our use case we need to capture each letter so it will be:

          
            step-1: str-slice("this is awesome",1 ,1) // t
            step-2: str-slice("this is awesome",2 ,2) // h
            step-3: str-slice("this is awesome",3 ,3) // i
            step-4: str-slice("this is awesome",4 ,4) // s
             ... 
            step-15: str-slice("this is awesome",15 ,15) // e
          
        
The final step is to place each captured letter in our empty variable ($reverse-string).
          
            step-1: $reverse-string // t
            step-2: $reverse-string // ht
            step-3: $reverse-string // iht
            step-4: $reverse-string // siht
             ... 
            step-15: $reverse-string // emosewa si siht
          
        

Pretty cool right?

More 'can we do that in SASS' tests in the following days. Cheers!