How to define konami code with Rx.js (reactive extensions for javascript)?

I want to start learning Rx.js , and I'm looking for a cool example to start rolling the ball. How to detect konami code using Rx.js?

I want to detect a sequence of keystroke events (up left left right right right BA) and display the image if that happens.

+8
reactive-extensions-js
source share
2 answers

Here is my version:

<html> <head> <script type="text/javascript" src="jquery-1.4.4.min.js"></script> <script type="text/javascript" src="rx.js"></script> <script type="text/javascript" src="rx.jQuery.js"></script> </head> <body> <p id="result"></p> <script type="text/javascript"> $(function() { var konami = $(document).toObservable("keyup").Select(function(e) { return e.keyCode }).SkipWhile(function(k) { return (k != 38) }).BufferWithCount( 10 ).Where(function(ks) { return ks.length == 10 && ks[0] == 38 && ks[1] == 38 && ks[2] == 40 && ks[3] == 40 && ks[4] == 37 && ks[5] == 39 && ks[6] == 37 && ks[7] == 39 && ks[8] == 66 && ks[9] == 65 }) var konamisub = konami.Subscribe(function(e) { $("#result").text("KONAMI!") $("#result").fadeIn().fadeOut() }) }) </script> </body> </html> 

I convert the keyup event stream to a stream of key codes using Select , and then ignoring the keystrokes until the user presses (key code 38) using SkipWhile , then collecting 10 keystrokes using BufferWithCount , then checking the keystrokes with using Where .

I tried using BufferWithTime, but it tends to get cut off in the middle of keystrokes.

If anyone can suggest improvements, I would like to hear them.

+7
source share

I don’t want to spoil your answer since you are learning, but I will try to think of the problem as “How to convert the Key up event to a sequence of the last 10 characters that were recently pressed” and compare this list with the permanent list “UUDDLRLRBA”. (Hint: Buffer, Where, Select, Take, Repeat, your friends are here)

+1
source share

Source: https://habr.com/ru/post/649762/


All Articles