Skip to content

Instantly share code, notes, and snippets.

@CarlMungazi
Last active November 3, 2018 21:22
Show Gist options
  • Save CarlMungazi/bf1bc3f22716a953226e to your computer and use it in GitHub Desktop.
Save CarlMungazi/bf1bc3f22716a953226e to your computer and use it in GitHub Desktop.
Many Ways To Split A String

Task: Reverse the provided string in as many different ways as possible.

Tests: All the solutions should pass the following tests:

  • "hello" should return a string.
  • "hello" should become "olleh".
  • "Howdy" should become "ydwoH".
  • "Greetings from Earth" should return "htraE morf sgniteerG"

Code:

1. All you need is one line of code

When I first came across this challenge on freecodecamp.org, this is the solution I came up with. It's pretty self-explanatory

function oneLinerReverse(str) { return str.split('').reverse().join(''); }

2. Using the humble for loop to do the work for us

Ah, the humble loop. It is not the cleanest way but it still gets the job done. To avoid using the .reverse() array method, we use the length of the split string and the count to re-assign the letters in reverse order and then join them

function forLoopOverString(str) {
  let strArr = []
  let newStr = str.split('');
  let count = 0;
  strArr.length = newStr.length

  for (count; count < newStr.length; count++) {
    strArr[newStr.length - count] = newStr[count] 
  }
  return strArr.join('')
}

3. Looping with charAt

Using charAt(), we can avoid doing any splitting and just simply target the specific characters we want to re-assign

function forLoopCharAt(str) {
  let strLen = str.length;
  let count = 0;
  let newStr = []

  for (count; count < strLen; count++) {
    newStr[strLen - count] = str.charAt(count)
  }
  return newStr.join('')
}

4. Poppin' & Pushin'

This method introduces the forEach loop, which is better than the for loop because we don't have to keep a count. We know this function will run for every item in the array. The pop() method returns the last element in the array so each time we do a loop, we just simply pop away.

function forEachPushPop(str) {
  let strArr = str.split('');
  let tempArr = [];
  
  str.split('').forEach(el => tempArr.push(strArr.pop()));
  return tempArr.join('');
}

5. Recursive Reversin'

I tried doing this myself for a bit and struggled, so I looked online to see how others have done it. Why does this work? Recursion creates a series of nested functions, so when the recursion is finished, the functions 'unwind' starting with the most inner nested function.

function recursiveReverse(str) {
  if (str === '') return ''; // base and terminal case
  return recursiveReverse(str.substr(1)) + str[0]; // the actual recursion
}

6. While Looping

What happens if you take the number two solution and replace it with a while loop?

function whileLooping(str) {
  let strArr = []
  let newStr = str.split('');
  let count = 0;
  strArr.length = newStr.length

  while (count < newStr.length) {
	strArr[newStr.length - count] = newStr[count] 	
	count++
    
  }
  return strArr.join('')
}

7. Do Whilin'

And if you use a do...while loop?

function doWhileLooping(str) {
  let strArr = []
  let newStr = str.split('');
  let count = 0;
  strArr.length = newStr.length

  while (count < newStr.length) {
	strArr[newStr.length - count] = newStr[count] 	
	count++
    
  }
  return strArr.join('')
}

8. Looping Down

Use a for loop but instead of counting up, count down. Also, no join('')! Taken from this

function doWhileLooping(str) {
  var newStr = "";
    for (var i = str.length - 1; i >= 0; i--) newStr += str[i];
    return newStr;
}

8. Modern reversing with ES6

Strings are iterable data structures, so we can use the new for..of loop. See this for more on for..of. I learnt this one here

function forOffin(str) {
  let reversedStr = "";
  for (let char of str) {
    reversedStr = `char${reversedStr}`
  }
  return reversedStr;
}

9. All you need is one...and some spread

Instead of using split('') to create an array from the string, we can spread the string characters into an array and then hand the array over to reverse() and join(''). I learnt this one here

function oneLineSpread(str) {
  return [..str].reverse().join('');
}

10. Reduced to nothing but a reversed string

When I first began this, I had a feeling you could use the reduce() method but I could not work it out until I came across this article.

function reducedAndReversed(str) {
  return str.split('').reduce((rev, char) => char + rev, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment