简体   繁体   中英

Is there a way to shorten a member function of an object conditionally in JavaScript?

I'm making a function which takes both .toArray() and without. Is there a conditional way to add this in es6, es7 or es8?

await db
   .collection(collection)
   .find(params)
   .toArray() //I want tis conditionally added or not

In the sense of this (this doesn't work)

   multiple && .toArray()

Or is this only possible on two methods?

Is there a way to shorten a member function of an object conditionally in JavaScript?

Not really. You have a chained set of methods and you can't insert something into the chain conditionally.

My sense is that the clearest option is this:

let x = db.collection(collection).find(params);
if (someCondition) x = await x.toArray();

There are other oddball things such as putting a no-op method on the object ahead of time and then executing a method from a variable that would sometimes contain "toArray" and sometimes contain "noop".

let x = await db.collection(collection).find(params)[someCondition ? "toArray" : "noop"]();

But, I don't think I'd ever write code this way myself as I don't see it as very clear.


FYI, your particular example is a little odd because .find() returns a cursor object and .toArray() returns a promise that resolves to an array. So, you're also asking to end up with different types of data one way vs. the other. It seems like this different result type is going to have to go down a different code path anyway so there's more to the conditional branch than just this one step. That indicates one should really look at the bigger picture for the overall problem than just this step or order to come up with the best solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM