Basic LISP Parser

It transforms a valid LISP expression into a JavaScript Object

by Génesis García Morilla

JavaScript

const parser = str => {
  let count = 0
  let arr = []
  let atom = []
  // Prepare array with atoms
  for (const s of str.slice(1, -1).split(' ')) {
    atom.push(s)
    if (s.includes('(')) count += s.match(/\(/g).length
    if (s.includes(')')) count -= s.match(/\)/g).length
    if (count == 0) {
      arr.push(atom.join(' '))
      atom = []
    }
  }
  // If atom with no brackets add in other case recursion
  return arr.reduce((obj, s, i) => {
    if (s.includes('(')) obj[`l${i}`] = parser(s)
    else obj[`l${i}`] = s
    return obj
  }, {})
}

// Examples (only valid expressions)
document.body.innerHTML =
['(a b c)', '(a b (c d (e)) (f))', '(a bc (d (ef) g) (hi))'].map(str => {
  const obj = parser(str)
  console.log(str)
  console.log(obj)
  return `<strong>${str}</strong> = <mark>${JSON.stringify(obj)}</mark>`
}).join('<br>')