in an error message, it's good to include a sneak peak of what the user typed next. it's a preview.
this language bites off "hi" or "hello". if you type something different, it shows you what you typed instead of "hi" or "hello". but it only shows you a snippet that's five CHARACTERS long so that it doesn't make the error message too long.
TRANSLATED:
give the term class a preview method that returns how many
CHARACTERS we should show in an error message.
class Term {
//...
preview(text) {
// return a string
}
}
then override it in the string term.
class StringTerm extends Term {
//...
preview(text) {
return text.slice(0, this.string.length)
}
}
then override it in the "or" term! we take the longest preview of the two terms so that we make sure we show enough (but not too much).
class OrTerm extends Term {
//...
preview(text) {
const preview1 = this.term1.preview(text)
const preview2 = this.term2.preview(text)
return preview1.length > preview2.length ? preview1 : preview2
}
}
now we can use it in the error message!!
class OrTerm extends Term {
//...
error(text) {
if (this.check(text)) {
return null
}
return `SHORT error: expected ${this.name()} but found '${text.slice(0, this.preview(text))}'!`
}
}
back to the dream