Recursively add to strings in JS

落爺英雄遲暮 提交于 2021-02-05 08:14:12

问题


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!

回答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!



回答2:


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!



回答3:


you can do that:

const greeting = n => n>0 ? 'Hi'+greeting(--n).toLowerCase() : '!'
 
console.log( greeting(3) ) // -> Hihihi!
console.log( greeting(5) ) // -> Hihihihihi!
console.log( greeting(-1)) // -> !
.as-console-wrapper { max-height: 100% !important; top: 0; }

if you are unfamiliar with ninja code :

function greeting(n)
  {
  if (n>0) return 'Hi'+ greeting(--n).toLowerCase() 
  else     return '!'
  }


来源:https://stackoverflow.com/questions/65856107/recursively-add-to-strings-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!