sometimes you want to bite off more than just two terms. you want to bite off as many as you want.
this language bites off "pasta" then it bites off "gang" then it bites off a number.
TRANSLATED:
it's easy. make a term that accepts MULTIPLE terms.
class ListTerm extends Term {
constructor(terms) {
super()
this.terms = terms
}
}
give it a name.
class ListTerm extends Term {
//...
name() {
return this.terms.map((term) => term.name()).join(" then ")
}
}
to bite, go through each term and try to bite it off the tail piece by piece. join the bites together. if any bite fails, give up.
class ListTerm extends Term {
//...
bite(text) {
let bite = ""
for (const term of this.terms) {
const [nextBite, nextTail] = term.eat(text)
if (nextBite === null) {
return null
}
bite += nextBite
text = nextTail
}
return bite
}
}
we should show the error of the failing bite. so go through again and pop out the failing term's error.
class ListTerm extends Term {
//...
error(text) {
for (const term of this.terms) {
const [nextBite, nextTail] = term.eat(text)
if (nextBite === null) {
return term.error(text)
}
text = nextTail
}
return null
}
}
then make your list.
const listTerm = new ListTerm([
new StringTerm("pasta"),
new StringTerm("gang"),
new NumberTerm(),
])
then use it.
function translate(text) {
return listTerm.translate(text)
}
back to the dream