Florent BRASSART
Florent BRASSART

Reputation: 33

What is the equivalent of this ternary operator expression?

I have to use a piece of code that comes from another company project. Unfortunately, it contains an expression that triggers an error in SonarCloud. The error is:

Non-empty statements should change control flow or have at least one side-effect

The colleague that wrote this line is not in the company anymore.

The line that needs to be modified is xhr.status === 200 ? observable.next(xhr.response), observable.complete()) : observable.error(xhr.statusText);.

Here is the full code:

  sendMedia(file: File, presignedUrl: string): Observable<Object> {
    return new Observable(observable => {
      const xhr = new XMLHttpRequest();
      xhr.open('PUT', presignedUrl, true);
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          xhr.status === 200 ?
            (observable.next(xhr.response), observable.complete()) :
            observable.error(xhr.statusText);
        }
      };
      xhr.send(file);
    });
  }

If this block equivalent to that statement?

if (xhr.status === 200) {
  return observable.next(xhr.response), observable.complete();
} else {
  return observable.error(xhr.statusText);
}

Thanks a lot for anyone trying to help!

Upvotes: 0

Views: 836

Answers (1)

Bala
Bala

Reputation: 1365

You are almost there except return statement

if (xhr.status === 200) {
  observable.next(xhr.response);
  observable.complete();
} else {
  observable.error(xhr.statusText);
}

Upvotes: 2

Related Questions