Reverse String for JavaScript: or The Extra Credit Heist

This is the first of many short blogs to help memorize code. Since I aspire to mastery with JavaScript, the examples will be with JS. A note about the format: it seems “scientifically proven” that people remember stories about people (especially absurd stories) much easier than they do dry facts. Now, let’s get memorizing a solution for that “reverse string” algorithm that makes use of reduce.

REMEMBER: reduce is a method you run on an array that will return a single value. There’s much in the documentation in the above link, with optional arguments, but for the sake of this algonalogy, below should give you a basic sense of how a reducer works.

const array1 = [1, 2, 3, 4];
const sampleReducer = (accumulator, currentValue) => accumulator + currentValue;
array1.reduce(sampleReducer) //this returns 10

array1.reduce(sampleReducer, 5) //this returns 15

The example below is the solution to reversing a string.

function reverse(str) {
  return str.split('').reduce((accumulator, currentValue) => {
    return currentValue + accumulator;
  }, '')
}

Now, how might we commit this algorithm to memory and perhaps even understand the basic functionality of reduce? With a tale of Allie and Cleff…

Picture yourself in high school… it’s time for the mid-term exam and Ms. Sneed promises to award the students extra credit on the final exam, in the order that they complete the test. In other words, if there are 10 students in the class, the one who finishes first will get 10 extra points.

However, Sneed doesn’t want anyone rushing through her allegedly difficult test and making it look easy. So in order to force students to take their time (but not too much) she has decreed that: if the student who finishes first has more than three errors on the exam, then the order of extra credit points (for everyone) will be reversed.

In Sneed’s class we’ve got: Allie, Jackie, Mary, and Beth. Michael, Wilhem, Roscoe, and Cleff. If they finished their exams in that exact order, their initials would make up a string "AJMBMRC". Thing is: Allie the class smartie is dating bad boy Cleff, the class moron. But, since Allie already has an awesome GPA, she decides to hell with the other students working hard for their extra credit… she decides to sacrifice herself by getting four questions wrong, that Cleff (who will most certainly finish last) will benefit from the reversal.

So, as everyone waits for Cleff to finish penciling his final wrongs answers in, Sneed notices that Allie has gotten the first three answers of the test wrong.

What then?

Let’s revisit the code, but a bit more personified in the story:

function reverseExtraCreditRule(theStudents) {
  return theStudents.split('').reduce((whoGetsTheMostExtraCredit, studentVictim) => {
    return studentVictim + whoGetsTheMostExtraCredit;
  }, '')
}

reverseExtraCreditRule("AJMBMRC") //returns CRMBMJA

To talk it out, in slow motion…

  • you have the function reverseExtraCreditRule, which takes an argument of theStudents
  • theStudents originally in tidy order (the string) are split mercilessly into an array, isolated as Sneed prepares to reorder them… in other words: theStudents.split('') transforms “AJMBMRC” into ['A','J','M','B','M','R','C']
  • Sneed then “reduces” the students, both (literally and figuratively).
  • Within reduce there will be the parameters for the new order: the accumulator (whoGetsTheMostExtraCredit), and the currentValue (studentVictim).
  • Allie, first among them, will also be first in the new order. Originally the one “who got the most extra credit” she will also be the first victim by her own hand.
  • After Allie takes her place on the new line, Jackie takes her place as the one whoGetsTheMostExtraCredit, but the moment is fleeting as Mary replaces Jackie, then Beth, then Michael, then Roscoe, and finally Cleff.

To revisit the code in a more self-evident way, consider the following with console.logs (NOTE: you’ll get the most value out of this if you actually run the snippets).

function reverseExtraCreditRule(theStudents) {
  console.log("The Students in order of completing the exam: ", theStudents)
  const studentsInConfusion = theStudents.split('')
  console.log("The students in isolation after being split: ", studentsInConfusion)
  return studentsInConfusion.reduce((whoGetsTheMostExtraCredit, studentVictim) => {
    console.log(" ")
    console.log("The original order: ", theStudents)
    console.log("The student victim: ", studentVictim)
    console.log("The new order: ", whoGetsTheMostExtraCredit)
    return studentVictim + whoGetsTheMostExtraCredit;
  }, '')
}

reverseExtraCreditRule("AJMBMRC")

The above code would return the following output:

The Students in order of completing the exam:  AJMBMRC
The students in isolation after being split:  [
  'A', 'J', 'M',
  'B', 'M', 'R',
  'C'
]
 
The original order:  AJMBMRC
The student victim:  A
The new order:  
 
The original order:  AJMBMRC
The student victim:  J
The new order:  A
 
The original order:  AJMBMRC
The student victim:  M
The new order:  JA
 
The original order:  AJMBMRC
The student victim:  B
The new order:  MJA
 
The original order:  AJMBMRC
The student victim:  M
The new order:  BMJA
 
The original order:  AJMBMRC
The student victim:  R
The new order:  MBMJA
 
The original order:  AJMBMRC
The student victim:  C
The new order:  RMBMJA
CRMBMJA

Lastly, to further expand on how this is working, if you had a string of names… the following would work:

function reverseExtraCreditFor(theStudents) {
  console.log("The Students in order of completing the exam: ", theStudents)
  const theNewStudents = theStudents.split(" ")
  let reversedOrder = theNewStudents.reduce((whoGetsTheMostExtraCredit, studentVictim) => {
    console.log(" ")
    console.log("The original order: ", theStudents)
    console.log("The student victim: ", studentVictim)
    console.log("The new order: ", whoGetsTheMostExtraCredit)
    return studentVictim + " " + whoGetsTheMostExtraCredit;
  }, '')
  return reversedOrder

reverseExtraCreditFor("Allie Jackie Mary Beth Michael Roscoe Cleff") //returns "Cleff Roscoe Michael Beth Mary Jackie Allie"

Discover more from Comedy Tragedy Epic

Subscribe now to keep reading and get access to the full archive.

Continue reading