Last active
July 9, 2020 14:58
-
-
Save spion/d003d41eb527b3b158db04f72b228896 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let Read = {}; | |
let End = {}; | |
function* lexer() { | |
let accumulatedChars = []; | |
while (true) { | |
let inp = yield Read; | |
if (inp === End) { | |
if (accumulatedChars.length > 0) yield accumulatedChars.join(''); | |
return; | |
} | |
if (inp === '(' || inp === ')') { | |
if (accumulatedChars.length > 0) { | |
yield accumulatedChars.join(''); | |
accumulatedChars = []; | |
} | |
yield inp; | |
} else accumulatedChars.push(inp); | |
} | |
} | |
function* syncAdapter(gen, iterable) { | |
let reader = gen(); | |
let currentVal = reader.next(); | |
if (currentVal.done) return; | |
for (let item of iterable) { | |
if (currentVal.value === Read) { | |
currentVal = reader.next(item); | |
} | |
while (currentVal.value !== Read && !currentVal.done) { | |
yield currentVal.value; | |
currentVal = reader.next(); | |
} | |
} | |
currentVal = reader.next(End); | |
while (!currentVal.done && currentVal.value !== Read) { | |
yield currentVal.value; | |
currentVal = reader.next(); | |
} | |
} | |
function* asyncAdapter(gen, iterable) { | |
let reader = gen(); | |
let currentVal = reader.next(); | |
if (currentVal.done) return; | |
for await (let item of iterable) { | |
if (currentVal.value === Read) { | |
currentVal = reader.next(item); | |
} | |
while (currentVal.value !== Read && !currentVal.done) { | |
yield currentVal.value; | |
currentVal = reader.next(); | |
} | |
} | |
currentVal = reader.next(End); | |
while (!currentVal.done && currentVal.value !== Read) { | |
yield currentVal.value; | |
currentVal = reader.next(); | |
} | |
} | |
let parseThis = 'a(bcd(ef)gh)ijk'.split(''); | |
let sa = syncAdapter(lexer, parseThis); | |
for (let production of sa) { | |
console.log(production); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment