Computer >> Computer tutorials >  >> Programming >> Javascript

Constructing a sentence based on array of words and punctuations using JavaScript


Problem

We are required to write a JavaScript function that takes in an array of words and punctuations. Our function should join array elements to construct a sentence based on the following rules −

  • there must always be a space between words;

  • there must not be a space between a comma and word on the left;

  • there must always be one and only one period at the end of a sentence.

Example

Following is the code −

const arr = ['hey', ',', 'and', ',', 'you'];
const buildSentence = (arr = []) => {
   let res = '';
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      const next = arr[i + 1];
      if(next === ','){
         res += el;
      }else{
         if(!next){
            res += `${el}.`;
         }else{
            res += `${el} `;
         }
      }
   }
   return res;
};
console.log(buildSentence(arr));

Output

hey, and, you.