我有过滤商品的问题。
是否有可能以某种方式更美妙地解决这种情况?
在这里,增加了一个参数,代码量增加了阶乘,所以我看到这样一个可怕的解决方案=)
let query = firebase.firestore().collection('products').orderBy('price')
// TODO: How I can rewrite it?
if (payload.category && payload.size && payload.color) {
query = query
.where('category', '==', payload.category)
.where('color', '==', payload.color)
.where('size', '==', payload.size)
} else if (payload.size && payload.color) {
query = query
.where('color', '==', payload.color)
.where('size', '==', payload.size)
} else if (payload.category && payload.color) {
query = query
.where('category', '==', payload.category)
.where('color', '==', payload.color)
} else if (payload.size && payload.category) {
query = query
.where('category', '==', payload.category)
.where('size', '==', payload.size)
} else if (payload.size) {
query = query
.where('size', '==', payload.size)
} else if (payload.category) {
query = query
.where('category', '==', payload.category)
} else if (payload.color) {
query = query
.where('color', '==', payload.color)
}
query.get() ...
答案 0 :(得分:2)
摆脱巨大的if / else结构,只为每个需要的内容添加query
。
let query = firebase.firestore().collection('products').orderBy('price')
if (payload.size) {
query = query.where('size', '==', payload.size)
}
if (payload.category) {
query = query.where('category', '==', payload.category)
}
if (payload.color) {
query = query.where('color', '==', payload.color)
}