Have you ever think about analysing the syntax of another computer language to use it in the one you are working with? We are going to transform a valid LISP expression (string) into a JavaScript object.
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>')
Homeworks: check if it’s a valid LISP expression.