match stream data using regular expression

We do not need full text available in order to match using regular expression, try https://www.npmjs.com/package/@yiminghe/regexp :

npm i @yiminghe/regexp

Then we can pull char from stream and match it by regular expression: https://codesandbox.io/s/match-stream-by-regular-expression-xd0xt

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";

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

您正在使用您的 WordPress.com 账号评论。 注销 /  更改 )

Google photo

您正在使用您的 Google 账号评论。 注销 /  更改 )

Twitter picture

您正在使用您的 Twitter 账号评论。 注销 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 注销 /  更改 )

Connecting to %s