Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RxJS with filter(Boolean) for queries?

I'm reading through some code with the snippet:

search(query: string) {
  of(query).
  pipe(
    filter(Boolean), 
    debounceTime(300), 

Is filter(Boolean) essentially the same thing as filter(v=>!!v)?

like image 705
Ole Avatar asked Dec 28 '18 02:12

Ole


2 Answers

Yes, they are the same.

   console.log(typeof Boolean); // prints function
   console.log(Boolean.prototype.constructor("truthy")); // prints true
   console.log(Boolean === Boolean.prototype.constructor); // prints true

The Boolean global reference points to the constructor function which returns a boolean value from the first argument.

The constructor can be used to create a boolean wrapper object, but it is not the same as the primitive true value.

    console.log(new Boolean("truthy")); // prints an object.
    console.log(new Boolean("truthy").valueOf() === true); // prints true
    console.log((new Boolean("truthy")) === true); // prints false
    console.log(Boolean("truthy") === true); // prints true

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

like image 176
Reactgular Avatar answered Oct 12 '22 11:10

Reactgular


They achieve the same result in that you don't get undefined values in your subscription.

The difference is that you lose Type Inference when using filter(Boolean)

const query = 'the query';

of(query).
  pipe(
     filter(Boolean)
  ).subscribe(val); // val here is of type 'Any'

of(query).
  pipe(
     filter(Boolean)
  ).subscribe((val: string)); // we can infer it back to string later

of(query).
   pipe(
      filter(v=> v!== undefined)
   ).subscribe(val); // val here is of type 'string' 
like image 15
Corey Downie Avatar answered Oct 12 '22 12:10

Corey Downie