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);
}
}
});
}