1

I'm tackling a recursion problem that returns a string of "hi"'s where the first "hi" has a capital H and the string ends with an exclamation point. I have the code below so far but I'm not sure how to prevent subsequent occurrences of "hi" having a capital H. Any guidance would be welcome.

function greeting(n) {
  if (n === 0) {
    return "";
  } else if (n === 1) {
    return "Hi!"
  } else {
    return `${'Hi' + greeting(n - 1)}`
  }
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!

2
  • I need it to return Hihihi! My current code capitalises all the H's Commented Jan 23, 2021 at 5:46
  • Just a .toLowerCase() is missing in your code. ${'Hi' + greeting(n - 1).toLowerCase()}. You don't need the n === 1 step. Commented Jan 23, 2021 at 13:57

2 Answers 2

1

One way to work around your problem is to pass a flag to the function which indicates whether this is the first call, and only in that case capitalise the hi. Note that you can simplify the code slightly by returning a ! when n == 0; then you don't need to special case n == 1:

function greeting (n, first = true) {
  if (n === 0) {
    return "!";
  } 
  else {
    return `${(first ? 'Hi' : 'hi') + greeting(n - 1, false)}`
  } 
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!

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

Comments

0

Just a .toLowerCase() is missing in your code.

`${'Hi' + greeting(n - 1).toLowerCase()}`

You don't need the n === 1 step.

function greeting(n) {
  if (n === 0) {
    return "!";
  } else {
    return `${'Hi' + greeting(n - 1).toLowerCase()}`
    //------------------------------^^^^^^^^^^^^^^
  }
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.