logo CodeStepByStep logo

collapseSequences

Language/Type: JavaScript recursion string

Write a recursive function named collapseSequences that accepts a string s and character (single-letter string) c as parameters and returns a new string that is the same as s but with any sequences of consecutive occurrences of c compressed into a single occurrence of c. For example, if we collapse sequences of 'a' in the string "aabaaccaaaaada", you get "abaccada".

Your function should be case-sensitive; if the character c is, for example, a lowercase 'f', your function should not collapse sequences of uppercase 'F' characters. In other words, you do not need to write code to handle case issues in this problem.

The following table shows several calls and their expected return values:

Call Returns
collapseSequences("aabaaccaaaaaada", 'a') "abaccada"
collapseSequences("mississssipppi", 's') "misisipppi"
collapseSequences("babbbbebbbxbbbbbb", 'b') "babebxb"
collapseSequences("palo alto", 'o') "palo alto"
collapseSequences("tennessee", 'x') "tennessee"
collapseSequences("", 'x') ""

Constraints:

  • Do not use any loops; you must use recursion.
  • Do not declare any global variables.
  • Do not use arrays.
  • You may define other "helper" functions if you like; they are subject to these same constraints.

Function: Write a JavaScript function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.