Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map sequence in Rx.JS

I would like to map correct sequence using Rx.js. A simplest example will be using keyboard. I attach Rx.js to keyboard events and waiting for three A no matter what will be between them, except Q. When sequence is matched I would like to print OK on console. For example:

  • AAA -> should print OK
  • AsssAqweA -> should print OK
  • AAQAAQ -> shouldn't print anything
  • AAQAAA -> should print OK
  • AAAsssAAAsssAAA -> should print three times OK

Should I use filter function and keep state inside it? Or there is an esier way to do that.

like image 320
Piotr Stapp Avatar asked Dec 06 '25 06:12

Piotr Stapp


1 Answers

You should be able to use the filter and scan operators to do what you want:

Rx.Observable.from("AsssAqweAbAAQAAA")

  // Only A and Q characters are important:

  .filter(char => (char === "A") || (char === "Q"))

  // Accumulate the A characters until there are three
  // or until a Q is received:

  .scan((acc, char) => {
    if ((char === "Q") || (acc.length === 3)) {
      acc = [];
    }
    if (char === "A") {
      acc.push(char);
    }    
    return acc;
  }, [])

  // Filter the accumulated characters until there
  // are three:

  .filter(acc => acc.length === 3)
  .mapTo("OK")
  .subscribe(value => console.log(value));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
like image 194
cartant Avatar answered Dec 07 '25 20:12

cartant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!