First Recursive Kata

Recursion is a very powerful tool in programming.  A recursive function is one which calls itself during its execution.  When I first looked at this I thought if it calls itself then will it go on forever?

In JavaScript one of the simplest examples is as follows:

function factorial(n) {

return n <= 1 ? 1 : n * factorial(n-1)

}

Essentially what is happening is that a function uses a ternary operator to evaluate if the value of n is less than or equal to 1 then the function returns 1, if it is not then the value n is multiplied again until we get to the desired result.  So the factorial of 5 is equal to 5 * 4 * 3 * 2 * 1, or 120.

The blurb from Code Academy says it best “In programming, factorials are a perfect example of a case when a recursive function should be used. Why? Because we are doing the same thing (multiplication) over again to a particular value (an integer) until we get the desired result.”

 

Now onto my recursive Kata.

The aim is to reverse a string and display it reversed for example hello will be olleh and alwin would be niwla.

So I decided to use built in substr method i.e substr(). My solution

function reverse(str) {

        return str.length === 1 ? str : reverse(str.substr(1)) + str.charAt(0);

}

A solution which I believed to be good but the clever and mot up voted solution was:

function reverse(str) {

        return str.length > 1 ? reverse(str.slice(1)) + str[0] : str;

}

This is similar and yet so much more cleverer than mine whilst I make sure that the string length is 1, this solution just states if the string is bigger than 1 then go on, it also makes use of the slice method which can be used to return selected elements in an array and not change the array.

 

Yes its good to learn

Leave a Reply

Your email address will not be published. Required fields are marked *