how do i repeat a letter number between two strings?

You would need to keep track of str between function calls. You could do this by storing the value of str in this using Function.prototype.bind, by adding an additional str parameter, or by using a global variable.

// Using Function.prototype.bind
function repeat_bind(n) {
  const str = this.str ?? '';
  if (n <= 0) return 'B' + str + 't'
  return repeat_bind.bind({ str: str + 'a' })(n - 1);
}
console.log('bind: ' + repeat_bind(5));


// Using additional parameter
function repeat_param(n, str = '') {
  if (n <= 0) return 'B' + str + 't'
  return repeat_param(n - 1, str + 'a');
}
console.log('parameter: ' + repeat_param(5));


// Using pre-existing global variable
let str = '';
function repeat_preglobal(n) {
  if (n <= 0) {
    const result = 'B' + str + 't';
    str = '';
    return result;
  }
  str += 'a';
  return repeat_preglobal(n - 1);
}
console.log('pre-existing global: ' + repeat_preglobal(5));


// Using ghost global variable (created and deleted)
function repeat_ghostglobal(n) {
  const str = window.str ?? '';
  if (n <= 0) {
    delete window.str;
    return 'B' + str + 't';
  }
  window.str = str + 'a';
  return repeat_ghostglobal(n - 1);
}
console.log('ghost global: ' + repeat_ghostglobal(5));

In my opinion, out of all of these options, using an additional parameter is the cleanest method to solve your problem.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top