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