Skip to content

Instantly share code, notes, and snippets.

@frostburn
Created December 3, 2023 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save frostburn/f8477fb4ce6bf912475ef5c8dd1ef932 to your computer and use it in GitHub Desktop.
Save frostburn/f8477fb4ce6bf912475ef5c8dd1ef932 to your computer and use it in GitHub Desktop.
Peggy proposition: Tagged template parser with auto-vectorization of template arguments
{{
function add(left, right) {
if (typeof left === 'number') {
if (typeof right === 'number') {
return left + right;
} else {
return right.map(r => left + r);
}
} else {
if (typeof right === 'number') {
return left.map(l => l + right);
} else {
return left.map((l, i) => l + right[i]);
}
}
}
}}
Start
= Expression
Expression
= left: Value '+' right: Value { return add(left, right); }
Value
= Int
/ FormattedTemplateArgument
Int
= [0-9]+ { return parseInt(text(), 10); }
FormattedTemplateArgument
= arg: €TemplateArgument { return typeof arg === 'number' ? arg : new Float64Array(arg) }
/**
Above €TemplateArgument is a new magic pattern that accepts the "hole" left by ${arg} inside backquotes and passes in the value as is.
Examples:
parse`1+2`
// Evaluates to 3.
parse`5+${3}`
// Evaluates to 8.
parse`5+${[1, 2, 3]}`
// Evaluates to Float64Array(3) [ 6, 7, 8 ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment