Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically chain methods to javascript function

I am using Google's Firestore for searching a database, and the logic is to name your source, then chain where() methods for each variable. An example of working code is:

var ref = firebase.firestore().collection('myCol');
ref.where('myVar1','==',true).where('myVar2','==',5).get()
.then((results) => {...})

The problem I'm having is I have no idea how to dynamically attach those where() methods (as the number of them will change with each different search). I suspect if I knew the name of it I'd be able to find it, but dot functions didn't show up much... How could I do this?

like image 271
xon52 Avatar asked Oct 26 '17 10:10

xon52


People also ask

Can you chain functions in JavaScript?

Function chaining is a pattern in JavaScript where multiple functions are called on the same object consecutively. Using the same object reference, multiple functions can be invoked. It increases the readability of the code and means less redundancy.

How does JavaScript method chaining work?

Method chaining happens when you want to call multiple functions using the same object and its reference. In the above example, the array method map returns an Array , which has a formidable number of methods. Because you return a reference pointing to an Array , you'll have access to all the properties of Array .

Can you chain string methods?

Although myString variable is actually a primitive string, JavaScript automatically converts primitives to String objects, so you can call String object methods on it. You can use the chaining method technique when you create either an object or a class.

Why do we use method chaining?

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.


1 Answers

From @Keith's reply below, I got it working using:

var vars = ['myVar1', 'myVar2', 'myVar3'];
var ref = firebase.firestore().collection('myCol');

vars.forEach(v => { ref = ref.where(v, '==', true) });

ref.get()
  .then(results => { ... })
  .catch(err => { ... })
like image 120
xon52 Avatar answered Sep 18 '22 18:09

xon52