Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Created October 19, 2020 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewRayCode/b3baf6532cbbb4e88fd426f94e719466 to your computer and use it in GitHub Desktop.
Save AndrewRayCode/b3baf6532cbbb4e88fd426f94e719466 to your computer and use it in GitHub Desktop.
right association peg.js
{
const node = (name, children) => ({
name,
children: [children].flat(),
});
const rightAssociate = (...nodes) => {
const [last, penultimate, ...flat] = nodes.flat().reverse();
return flat.reduce((current, previous) => node(
current.name,
[...(previous.children || [previous]), current]
), node(last.name, [...penultimate.children, ...last.children]));
}
}
start = right_assoc_exprs
num = $[0-9]+
right_assoc_exprs = head:num tail:(
'||' val:num { return node('or', val) }
)* {
return tail.length ?
rightAssociate(head, tail) :
head;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment