Reduced code duplication when handling full line tags

This commit is contained in:
Ben Ashton 2022-09-03 01:28:35 -06:00
parent 09c3942f34
commit dece3c5934
3 changed files with 29 additions and 37 deletions

View File

@ -18,6 +18,7 @@ $ title='My Restaurant Randomizer';
<h1>Welcome to <% $title %></h1>
<p>From the following restaurants:</p>
<ul>
# Loop through restaurants and display each one
$ while read restaurant; do
<li><% $restaurant %></li>
$ done <restaurants.txt
@ -48,6 +49,7 @@ printf '%s' "$title" | jq -Rrj @html;
printf '%s\n' '</h1>';
printf '%s\n' ' <p>From the following restaurants:</p>';
printf '%s\n' ' <ul>';
# Loop through restaurants and display each one
while read restaurant; do
printf '%s' ' <li>';
printf '%s' "$restaurant" | jq -Rrj @html;
@ -82,7 +84,7 @@ Which when executed might produce the following HTML:
</ul>
<p>
The fates have decided that you shall eat at:
<strong>Papa Johns</strong>
<strong>Luigi&apos;s</strong>
</p>
</body>
</html>

View File

@ -9,6 +9,7 @@ $ title='My Restaurant Randomizer';
<h1>Welcome to <% $title %></h1>
<p>From the following restaurants:</p>
<ul>
# Loop through restaurants and display each one
$ while read restaurant; do
<li><% $restaurant %></li>
$ done <restaurants.txt

View File

@ -144,60 +144,49 @@ export class TokenStream {
);
}
_readStatement() {
_missingFullLineSpaceError(tag) {
throw new TemplateSyntaxError(
this._cs,
`Full-Line Tag: "${tag}" must be followed by a whitespace`
);
}
_readFullLineGeneric(tokenType, tag) {
// Skip whitespace
this._cs.nextWhile(this._isWhitespace);
// Skip STATEMENT
this._cs.next();
// Skip tag
this._cs.next(tag.length);
// Check for mandatory space
if (this._cs.peek() !== ' ') {
throw new TemplateSyntaxError(
this._cs,
`Statement character: "${TokenStream.STATEMENT}" must be ` +
`followed by a whitespace`
);
this._missingFullLineSpaceError(tag);
}
// Consume space
this._cs.next();
// Remainder of line is statement
// Remainder of line is value
const value = this._cs.nextWhile((c) => c !== '\n');
// Swallow new line
// Skip new line
this._cs.next();
return {type: 'statement', value};
return {type: tokenType, value};
}
_readStatement() {
return this._readFullLineGeneric(
'statement',
TokenStream.STATEMENT
);
}
_readComment() {
// Skip whitespace
this._cs.nextWhile(this._isWhitespace);
// Skip COMMENT
this._cs.next();
// Check for mandatory space
if (this._cs.peek() !== ' ') {
throw new TemplateSyntaxError(
this._cs,
`Comment character: "${TokenStream.COMMENT}" must be followed by a ` +
`whitespace`
);
}
// Consume space
this._cs.next();
// Remainder of line is comment
const value = this._cs.nextWhile((c) => c !== '\n');
// Swallow new line
this._cs.next();
return {type: 'comment', value};
return this._readFullLineGeneric(
'comment',
TokenStream.COMMENT
);
}
// Utility methods