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:
Should I use filter function and keep state inside it? Or there is an esier way to do that.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With