Get Fit with Dynamic Programming

Currently delving into the realm of reactive programming using RxJS, I encountered the following exercise:

  • Initialization of an empty array
  • Upon application launch, a new Date() is added to the array
  • Each mouse click appends a new value to the array along with the date of the click
  • Upon reaching an array length of 3, perform the calculation:      (array[2].valueOf() + array[1].valueOf() - array[0]) % 2
  • If the result equals 0, display 'Result valid'
  • Subsequently, if a new element is added to the array after the calculation, the first element is removed, shifting the rest and placing the new element at the end

While exploring both the declarative and reactive methodologies for this exercise, I found the reactive approach lacking true reactivity due to the presence of multiple if/else statements and complex logic within the subscriber.

Here lies my question: Is the code within the function exercise_1__v2_reactive truly reflective of reactive programming principles?

function exercise_1__v1_imperative() {
    let values: Array<Date> = [];
    values.push(new Date());

    document.addEventListener(`click`, () => {
        values.push(new Date());
        console.log(`values: `, values);

        if (values.length === 3) {
            let a = values[0].valueOf(), b = values[1].valueOf(), c = values[2].valueOf();
            let result = (c - b + a) % 2;
            console.log(`result: `, result);

            if (result === 0) {
                console.log(`Resultado valido: `, result);
            }

            values.shift();
        }
    });
}

function exercise_1__v2_reactive() {
    const newDate$ = of(new Date().valueOf());
    // newDate$.subscribe(console.log);

    const clickDate$ = fromEvent(document, `click`).pipe(
        map(x => new Date())
    );

    clickDate$.pipe(
        startWith(new Date()),
        scan<Date, Array<Date>>((acc, value) => {
            if (acc.length === 3) {
                acc.shift();
            }

            acc.push(value);
            return acc;
        }, [])
    ).subscribe(values => {
        console.log(values);

        if (values.length === 3) {
            let a = values[0].valueOf(), b = values[1].valueOf(), c = values[2].valueOf();
            let result = (c - b + a) % 2;
            console.log(`result: `, result);

            if (result === 0) {
                console.log('Resultado valido: ', result);
            }
        }
    });
}

Answer №1

Indeed, your exercise_1__v2_reactive function appears to be in good shape from an rxjs standpoint, with room for slight enhancement. By eliminating the startWith method and opting for the filter operator instead to only emit an array of length 3, the function can be refined as follows:

function exercise_1__v2_reactive() {
  fromEvent(document, 'click')
                  .pipe(
                    mapTo(new Date()),
                    scan((acc: any, val) => {

                        if (acc.length === 3) {
                          acc.shift();
                        }
                        acc.push(val);
                        return acc;
                    }, []),
                    filter(a => a.length === 3),
                    //Tap is just to check what my array is - But its not needed
                    tap(console.log),
                    map(values => {
                        const result = (values[2].valueOf() - values[1].valueOf() + values[0].valueOf()) % 2;

                        console.log(`result: `, result);

                        if (result === 0) {
                            return 'Result Valid';
                        }
                        return 'Result Invalid';
                    })
                  ).subscribe(console.log);
}

As seen, the usage of startWith has been omitted and the final outcome is now being mapped to the desired string. The approach for projecting the end result can vary based on the specific requirements.

Answer №2

After my extensive research on the RxJS operators, I found that using the bufferCount operator with the parameters bufferCount(3, 1) will provide the solution. The second parameter determines when to initiate a new buffer, in this case, it will be after every click:

fromEvent(document, 'click').pipe(
  map(_ => new Date()),
  startWith(new Date()),
  bufferCount(3, 1),
  map(([a, b, c]) => (c.valueOf() - b.valueOf() + a.valueOf()) % 2),
  tap(val => console.log('TAPPING: ', val)),
  filter(x => x === 0)
).subscribe(valid => {
  console.log('Result valid')
});

You can find the solution in the following URL: https://stackblitz.com/edit/rxjs-q3aneg

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes a ReactJS component to disappear upon page refresh?

After the user clicks the Login button in the Instructor Login Form, I want to display the Instructor Profile component. Everything functions properly until I refresh the page, at which point the User Profile component disappears. Here is a screenshot of ...

Ways to serve JSON response following a 400 error code

After a user submits incorrect form details, such as an invalid username or blank email address, I make an Ajax request to my REST API. The response data I receive is structured as follows: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: applicati ...

Creating a 24-hour bar chart using Flot Javascript, showcasing data points at each hour mark

I am attempting to create a 24-hour bar graph using Flot Charts, with a value corresponding to each hour. It seems that Flot utilizes epoch time for hour values. However, after running the code below, I encounter an issue where the chart does not display a ...

Encountering a Jquery 404 error while attempting to locate a PHP file through Ajax requests

I've been struggling with this issue for the past couple of hours, but I just can't seem to get it fixed. Here's my current file setup: classes -html --index.html --front_gallery.php -javascript --gallery.js I've been following a tuto ...

What is the best way to achieve this in Node.js/Express using Redis? Essentially, it involves saving a callback value to a variable

Here is the data structure I have set up in redis. I am looking to retrieve all values from the list and their corresponding information from other sets. Data structure : lpush mylist test1 lpush mylist test2 lpush mylist test3 set test1 "test1 value1" ...

Issue encountered while utilizing JQueryUI alongside TypeScript and the definition file from DefinitelyTyped

Currently, I'm attempting to incorporate JQueryUI with TypeScript by first installing JQueryUI using npm install jquery-ui-dist, and then installing JQuery with npm install jquery. Additionally, I have included the definition files from DefinitelyType ...

Retrieve the screen width using a JavaScript function and apply it as a percentage

I find myself needing to adjust the size of table elements based on the width of the screen. While I am not well-versed in javascript or html, resolving this issue is crucial. Unfortunately, I did not create the original asp page and have limited ability t ...

Angular $resource failing to transfer parameter to Express endpoint

I am currently working on an Angular application that needs to retrieve data from a MongoDB collection. To accomplish this, I am utilizing the $resource service within the flConstruct. The "query" function works well as it returns all data from the server ...

Experiencing challenges with ng-repeat and the concept of 'distinct'

I'm facing a perplexing issue. When utilizing ng-repeat to iterate through my data and create checkboxes, I encounter unexpected behavior. The result is multiple duplicate items being displayed instead of unique ones. Here's an example: <lab ...

Adding additional validations to your Marketo form is a great way to ensure the accuracy

I'm having trouble adding a new validation rule to the Marketo form since I'm not well-versed in JS and jQuery. I need this rule to display an error message if the form is submitted with any field left empty. Additionally, I want to validate the ...

Expanding the width of CSS dropdown menus according to their content

When attempting to create a dynamic dropdown menu, I encountered an issue where the values were skewed in Internet Explorer if they exceeded the width of the dropdown. To fix this problem, I added select:hover{width:auto;position:absolute}. However, now th ...

Determine if the html element is wrapping to a new line when zoomed in or when the text size on Windows is increased

My webpage has 2 labels displayed side by side, but due to the system text size being set at 150% (which is recommended) in Windows, the second label does not have enough space and gets pushed below the first label. I am looking for a way to determine if t ...

The knockout click event isn't functioning properly for a table generated by ko.computed

My goal is to connect a table to a drop-down menu. Here are the key points of what I'm trying to achieve: The drop-down should list MENUs. Each MENU can have multiple MODULES associated with it, which will be displayed in the table based on the ...

"Utilizing three.js to smoothly move the camera forward with a left mouse click

I am currently working on a 3-D graphical website using three.js. The theme of the website is a universe filled with text. My goal is to make the camera move forward when the left mouse button is clicked and backward when the right mouse button is clicked. ...

Scroll the table automatically when the currently selected row is the second-to-last row

Having trouble with a scrolling table issue. https://i.sstatic.net/PFyN3.png Upon page load, the first row (ROW 1) is automatically selected and highlighted. Clicking the next button selects and highlights the subsequent rows. However, once ROW >= 8 (e ...

Is there a way to create a multi-page website simulation using jQuery?

My current project involves creating a single page website, but I am looking to give the illusion of a multi-page site by using CSS/jQuery to hide and reveal different sections when specific links in the navigation menu are clicked. Here is the code snipp ...

The mistake is indicating the npm title of a package that is not present

https://i.sstatic.net/5bywN.png An issue has arisen - the module cannot be found, even though such a module does not actually exist. The correct module name should be babel-plugin-proposal-class-properties (and the error is showing as 'babel-plugin-t ...

Ending JavaScript promises

I am currently utilizing the Google JS closure library which can be found at https://developers.google.com/closure/library/ Below is the code snippet that I have: if (endDate >= wap.com.ifx.util.IfxComponentUtil.yyyymmdd(currentDate) && goog.o ...

Learn the process of utilizing Uglify.js to combine JavaScript files for individual views within Express.js

My website is currently built on express.js and I am looking to optimize my JavaScript files using uglify.js in the build process. An example of a typical view on my site appears as follows: extend layout block head script(src="/js/polyfills/html5s ...

Utilizing JavaScript Plugin to Fix Image Source URLs in Incorrect Directories

I'm struggling and really in need of some assistance. The issue I'm facing is with a plugin that has a JavaScript file containing an array of URLs pointing to a "texture" directory within the plugin for images. However, I keep encountering 404 e ...