Skip to content

Instantly share code, notes, and snippets.

@yiminghe
Created September 14, 2021 10:00
Show Gist options
  • Save yiminghe/240036e19ffd9a7f4de7fc79eacbaab2 to your computer and use it in GitHub Desktop.
Save yiminghe/240036e19ffd9a7f4de7fc79eacbaab2 to your computer and use it in GitHub Desktop.
import * as regexp from "@yiminghe/regexp";
(async function () {
const fakeData = ["x", "a", "b", "c", "a", "a", "b"];
let index = 0;
let length = fakeData.length;
let promise;
let stream = [];
// push data to steam
setInterval(() => {
stream.push(fakeData[index++ % length]);
if (promise) {
const { resolve } = promise;
promise = null;
resolve();
}
}, 500);
const patternInstance = regexp.compile("a+b", { async: true });
const matcher = patternInstance.matcherAsync(() => {
// fetch data from stream
return new Promise((resolve) => {
function r() {
if (stream.length) {
resolve(stream);
stream = [];
}
}
if (stream.length) {
r();
} else {
// waiting for data
promise = {
resolve: r
};
}
});
});
while (true) {
const { match } = await matcher.match();
console.log("match: ", match);
}
})();
document.getElementById("root").innerHTML = "open console";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment