user3445122 user3445122 - 4 months ago 24
Javascript Question

Printing triangle with word characters in JavaScript using recursion only

Interview Question: I was asked to write a recursive JavaScript function that takes an P character long String as input, and prints out the following:


  1. The first line prints the first character of the string

  2. The second line prints the first two characters of the string

  3. and so on until Pth line prints all the characters of the string

  4. (P+1)th line prints first (P-1) characters

  5. (P+2)th line prints first (P-2) characters

  6. and so on until (2P -1) th line prints only the first character



And if we run the function : printTriangle("A Joke")

It will printout the following:

A

A

A J

A Jo

A Jok

A Joke

A Jok

A Jo

A J

A

A

I was asked to write this function in the interview, I could only write using iterative approach. Still wondering how to write that using recursive approach, can anyone enlighten?

Answer

Here is my solution:

function triangle(str, i) {

  if(i === 0) return;
    
  i = i || 1;
    
  if(i > str.length) return triangle(str, -1*str.length+1) ;
    
  console.log(str.substr(0, Math.abs(i)));
    
  return triangle(str, i+1) ;
}

triangle("A Joke");

Comments