Z
Z
zlodiak2018-02-23 12:50:29
JavaScript
zlodiak, 2018-02-23 12:50:29

Why is the result from Observable not displayed?

I tried to implement Observable in native js, but I couldn't get the expected result. This code outputs undefined instead of the result. Please help me fix the code.

class Observable{
  
  constructor(source) {
    this.source = source.split('');
    this.result = this.source;
  }

  subscribe(next) {
    for(let item of this.result) {
      next(item);
    }
  }

  filter(predicate) {
    this.result = this.result.filter(predicate);
    return this;
  }

  map(callback) {
    this.result = this.result.map(callback);
    return this;
  }	

}

new Observable('qwerty')
  .map((letter) => { letter.toUpperCase() })
  .filter((letter) => { letter === 'W' })
  .subscribe((letter) => { console.log(letter) });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-23
@zlodiak

This code outputs undefined instead of the result.

By "outputs" you mean the result of calling console.log, right? Well, your code doesn't output anything - console.log is never called, undefined is thrown in the console because the last thing you do is call the subscribe method, which returns nothing.
The absence of output is due to the emptiness of the result array, and it is empty because ... No, I will not explain - figure out how to use arrow functions and find your mistakes yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question