Analytics SDK

Implement an analytics SDK that exposes log events, it takes in events and queues them, and then starts sending the events.

  1. Send each event after a delay of 1 second and this logging fails every n % 5 times. (Stub Function)
  2. Stub is a function definition that has correct function name, the correct number of parameters and produces dummy result of the correct type. It helps to write the test.
  3. Send the next event only after the previous one resolves.
  4. When the failure occurs attempt a retry.
class SDK {
  constructor(n) {
    this.logs = [];
    this.retryAfter = n;
    this.count = 1;
  }

  log(event) {
    this.logs.push(event);
  }

  wait() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (this.count % this.retryAfter === 0) {
          reject();
        } else {
          resolve();
        }
      }, 1000);
    });
  }

  sendAnalyticsSDK = async () => {
    if (this.logs.length === 0) return;

    let current = this.logs.shift();
    try {
      await this.wait();
      console.log("Analytics Send: ", current);
      this.count++;
    } catch (err) {
      console.log("-----");
      console.log("Failed: ", current);
      console.log("Retrying: ", current);
      console.log("-----");
      this.logs.unshift(current);
      this.count = 1;
    } finally {
      this.sendAnalyticsSDK();
    }
  };
}

const sdk = new SDK(5);
sdk.log("Event 1");
sdk.log("Event 2");
sdk.log("Event 3");
sdk.log("Event 4");
sdk.log("Event 5");
sdk.log("Event 6");
sdk.log("Event 7");
sdk.log("Event 8");
sdk.log("Event 9");
sdk.log("Event 10");
sdk.log("Event 11");
sdk.log("Event 12");
sdk.log("Event 13");
sdk.log("Event 14");
sdk.log("Event 15");
sdk.sendAnalyticsSDK();
Analytics Send:  Event 1
Analytics Send:  Event 2
Analytics Send:  Event 3
Analytics Send:  Event 4
-----
Failed:  Event 5
Retrying:  Event 5
-----
Analytics Send:  Event 5
Analytics Send:  Event 6
Analytics Send:  Event 7
Analytics Send:  Event 8
-----
Failed:  Event 9
Retrying:  Event 9
-----
Analytics Send:  Event 9

Analytics Send:  Event 10
Analytics Send:  Event 11
Analytics Send:  Event 12
-----
Failed:  Event 13
Retrying:  Event 13
-----
Analytics Send:  Event 13
Analytics Send:  Event 14
Analytics Send:  Event 15