Skip to content

Latest commit

 

History

History
70 lines (49 loc) · 1.8 KB

File metadata and controls

70 lines (49 loc) · 1.8 KB

72. implement Observable interval()

Problem

https://bigfrontend.dev/problem/implement-Observable-interval

Problem Description

This is a follow-up on 57. create an Observable.

Suppose you have solved 57. create an Observable, here you are asked to implement a creation operator interval().

From the document, interval()

Creates an Observable that emits sequential numbers every specified interval of time

interval(1000).subscribe(console.log);

Above code prints 0, 1, 2 .... with an interval of 1 seconds.

Note Observable is already given for you, no need to create it.

Understanding the problem

I am asked to write a function called interval(period). The function should create an Observable that will emit an infinite sequence of ascending integers, starting from 0, every specified interval of time. The class Observable is provided to me.

Approach

To create a Observable, I need to provide a callback as setup to the new Observable constructor, such as:

const observable = new Observable((subscriber) => {
  subscriber.next(1);
  subscriber.next(2);
  setTimeout(() => {
    subscriber.next(3);
    subscriber.next(4);
    subscriber.complete();
  }, 100);
});

And in order to emit an infinite sequence of ascending integers, I can initialize a variable that is going to store the current integer.

Solution

/**
 * @param {number} period
 * @return {Observable}
 */
function interval(period) {
  let num = 0;
  return new Observable((subscriber) => {
    setInterval(() => {
      // subscriber.next(num++);
      subscriber.next(num);
      num++;
    }, period);
  });
}