The main thing in any sorting function is the ability to compare two strings and check which of the two must go before the other. Almost every programming language has some in-built sort functions, but to do this in Sass you need to create your own string comparison function. In the first step, we need to teach Sass, the correct order of sorting the strings based on the characters each string contains. We do this using a variable.
This will be used to declare that strings that begin with a should appear before strings that begin with b or c and so on. You may also add other values like numbers, capital letters or symbols.
Now, you will be needing a comparison function. In the comparison function we basically loop across the characters in each string and look up their order in the sort-order list with the help of the Sass index() function. It will give us two values that can be compared which one of them goes before the other. If the values are same, we loop around the next set of characters, and so on.
The str-compare() function returns true if $string-a goes before $string-b and false if it does not.
Here, we will be using Bubble Sort algorithm for sorting as it is the most basic and easy approach. Since bubble sort is based on swapping two values in the array or list, we will also be needing a swap() function in Sass.
The swap() function will take a list and two index values as input. The index values need to be swapped in the list.
We will be using the set-nth() function, as it simply just updates the list rather than creating a new list.
Now, we have a compare() function as well as a swap() function, meaning we are ready to create our sort() function. The function simply loops through the list, compares items with each other and swaps them once compared until the list is completely sorted.
Finally we need to pass the string values and return sort() function.
classes courses geeksforgeeks internships placements