Skip to content

Instantly share code, notes, and snippets.

@hildjj
Forked from frostburn/tagged-vector-adder.pegjs
Last active December 3, 2023 20:08
Show Gist options
  • Save hildjj/acd124e55ee1ce4cf4633e33370a1bb3 to your computer and use it in GitHub Desktop.
Save hildjj/acd124e55ee1ce4cf4633e33370a1bb3 to your computer and use it in GitHub Desktop.
Peggy proposition: Tagged template parser with auto-vectorization of template arguments
import peg from "peggy-tag";
const PLACEHOLDER = "{{{ARG}}}";
const parse = peg`
{{
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
= "${PLACEHOLDER}" {
const arg = options.args[offset()];
return typeof arg === 'number' ? arg : new Float64Array(arg)
}
`;
function p(strings, ...values) {
let text = "";
const args = {};
strings.forEach((string, i) => {
text += string;
if (i < values.length) {
args[text.length] = values[i];
text += PLACEHOLDER;
}
});
return parse(text, { args });
}
console.log(p`${6}+${[2, 3]}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment