0

I am working to improve recursion skills, and took a crack at the recursive function below.

However, I'm looking to improve the implementation (and thus my understanding) by eliminating the necessity of the i iterator as a second parameter to correcter. I feel like the function as is at the moment is still very iterative, if that makes sense.

How would I go about specifically eliminating this from the function, and still use use a recursive function to run the same operation successfully?

Thanks!

// Transform an array of items, correcting gramatically 

var capitals = ["MaDRid", "paRIs", "SantIAgO"]

var correcter = function(array, i) {

  var transform = function(city) {
  	return city.charAt(0).toUpperCase() + city.slice(1).toLowerCase();
  }
    
  // base case 
  if (array.length === i) {
  	return array;
  }

  // action 
  array[i] = transform(array[i]);

  // recursive case
  return correcter(array, i + 1);
};

correcter(capitals, 0);

1
  • It is not a very good use case for using recursion, even as a study object. You have a list of items and a known length. Would have been different if it was about processing nested arrays or something like that. This just begs for using Array#map Commented Nov 5, 2015 at 22:19

2 Answers 2

1

You pass in an array, with each level passing in one less of the array. When the array is empty, return. concat will take care of adding or not adding anything to the resulting array (concat does nothing if you concat an empty array).

var capitals = ["MaDRid", "paRIs", "SantIAgO"]

function correcter(array){

  var city = array[0];
  if(!city) return [];
  var correctedCity = city.charAt(0).toUpperCase() + city.slice(1).toLowerCase();

  return [correctedCity].concat(correcter(array.slice(1)));
}

var corrected = correcter(capitals);

document.write(JSON.stringify(corrected));

Sign up to request clarification or add additional context in comments.

Comments

1

Here how you can make i optional. If i is not passed then we start from 0. if it's passed then we use it to traverse. Also take transform out of the recursive function this way it's defined only ones.

var capitals = ["MaDRid", "paRIs", "SantIAgO"]

function transform (city) {
  return city.charAt(0).toUpperCase() + city.slice(1).toLowerCase();
}
function correcter (array, i) {
  if ( i == null) { // <- i is optional now
    i = 0;
  }

  // base case 
  if (array.length === i) {
    return array;
  }

  // action 
  array[i] = transform(array[i]);

  // recursive case
  return correcter(array, i + 1);
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.