Properly formatted JavaScript code


#1
function prettyJson(str) {
  const stack = []
  let answer = ''
  for(let i = 0; i < str.length; i++) {
    if(isCloseBrace(str[i])){
      stack.pop() 
      answer += '\n'
      answer += tabs(stack.length)
      answer += str[i]
    }
    else if(isOpenBrace(str[i])) {
      answer += '\n'
      answer += tabs(stack.length)
      answer += str[i]
      stack.push(str[i])
    }
    else {
      if(str[i] !== ',') {
        answer += '\n'
        answer += tabs(stack.length)
      }
            
      while(str[i] !== ',' && !isOpenBrace(str[i]) && !isCloseBrace(str[i])) {
        answer += str[i]
        i++
      }
      if(str[i] === ',') {
        answer += str[i]
      }
      else {
        i--  
      }
    }
  }

  const [first, ...rest] = answer.split('\n')
  return rest
}

function tabs(size) {
  let str = ''
  while(size--) {
    str += '\t'  
  }
  return str
}

function isOpenBrace(char) {
  return char === '{' || char === '['  
}

function isCloseBrace(char) {
  return char === '}' || char === ']'  
}