DEV Community

Cover image for Parser Combinators are Easy

Parser Combinators are Easy

Ben Lovy on February 05, 2019

Let's say we've been sent some brand new points. However, the Point Guru is having a burst of 'creativity' today and has devised a crazy transmiss...
Collapse
 
qm3ster profile image
Mihail Malo • Edited

Nice grammar you got there.
So... regular.
Would be a shame if something...

const HappenedToIt = input => {
  const re = /\d+|\)\]\[\(|\]\[/g
  const out = [[[]]]
  let set = out[0]
  let point = set[0]
  let match
  while ((match = re.exec(input))) {
    const [m] = match
    switch (m) {
      case ")][(":
        out.push((set = []))
      case "][":
        set.push((point = []))
        continue
    }
    point.push(parseInt(m, 10))
  }
  return out
}
console.log(
  JSON.stringify(
    HappenedToIt(".:{([2 3]][[6 2]][[1 2])][([1 4]][[2 1])][([6 9])}:.")
  )
)
Collapse
 
deciduously profile image
Ben Lovy • Edited

Point Guru wasn't so bonkers after all ;)

Perhaps a more interesting input would have been warranted

Collapse
 
thermatix profile image
Martin Becker • Edited

At least for paired tokens, I probably would have used a pushdown automata.

Thread Thread
 
qm3ster profile image
Mihail Malo

I only looked at the separators, not the paired wrappers.
Furthermore I didn't rely on the knowledge that the points are 2-dimensional.

You could say I have a stack of stacks of stacks :v

Thread Thread
 
deciduously profile image
Ben Lovy

Points could just be space separated, the sepBy() combinator would address that restriction

Thread Thread
 
qm3ster profile image
Mihail Malo • Edited
 2      number
 3      number
 ][     new point
 6      number
 2      number
 ][     new point
 1      number
 2      number
)][(    new set
 ][     new point
 1      number
 4      number
 ][     new point
 2      number
 1      number
)][(    new set
 ][     new point
 6      number
 9      number
Collapse
 
adambrandizzi profile image
Adam Brandizzi

Man, this is a lovely parser library---and a neat explanation. Thanks for this post!

Collapse
 
qm3ster profile image
Mihail Malo

FIRST COMMENT