if(weekly_trending === "true" && monthly_trending === "true"
&& quarterly_trending === "true"
&& sort_by_likes === "true"
&& sort_by_date === "true" ){
return
}
這些是我想在我的 api 中使用的過濾器,但我想允許一次只使用其中一個過濾器,比如只使用 week_trending === "true" 而不是串列中的任何其他過濾器,我可以使用這樣的 if 陳述句來做到這一點但是我必須寫這么多代碼,還有其他解決方案嗎?提前致謝
我嘗試過使用 if 陳述句,但我必須寫這么多,所以有沒有其他解決方案
uj5u.com熱心網友回復:
創建一個幫助類驗證器以根據需要添加規則并驗證結果。
const weekly_trending = true;
const monthly_trending = true;
const quarterly_trending = true;
const sort_by_likes = true;
const sort_by_date = true;
class Validator {
constructor() {
this.rules = [];
}
addRules(...rules) {
this.rules.push(...rules);
}
validate() {
if (this.rules.every(rule => rule === true)) {
console.log("all true");
}
}
}
const validator = new Validator();
validator.addRules(
weekly_trending,
monthly_trending,
quarterly_trending,
sort_by_likes,
sort_by_date
);
validator.validate();
uj5u.com熱心網友回復:
你可以做的就是從你所有的布林值創建一個陣列,并array.filter得到一個全部等于 true 的陣列
var conditions = [
weekly_trending,
monthly_trending,
quarterly_trending,
sort_by_likes,
sort_by_date
];
conditions.filter(condition => condition)
array.filter 是一種方法:
- 迭代陣列元素
- 應該回傳 true 或 false 為所有他們接受回呼傳入引數
- 最后它回傳另一個陣列,其中存在匹配條件等于 true 的元素
你if可以簡化為
if(conditions.filter(condition => condition).length === 1){
var weekly_trending = true;
var monthly_trending = false;
var quarterly_trending = false;
var sort_by_likes = false;
var sort_by_date = false;
function getConditions() {
return [
weekly_trending,
monthly_trending,
quarterly_trending,
sort_by_likes,
sort_by_date
];
}
function validate() {
var conditions = getConditions();
if(conditions.filter(condition => condition).length === 1) {
console.log('win');
} else {
console.log('failed');
}
}
validate();
monthly_trending = true;
validate();
uj5u.com熱心網友回復:
將您的規則添加到陣列中,并創建一個函式來獲取規則陣列并檢查它們是否都為真
const rules = [weekly_trending, monthly_trending, quarterly_trending, sort_by_likes, sort_by_date]
if (validator(rules)) {
// do something
}
function validator(rules){
if (rules.every(rule => rule === "true")){
return true
}
return false
}
或者如果您喜歡撰寫更少的代碼,您可以這樣做
const rules = [weekly_trending, monthly_trending, quarterly_trending, sort_by_likes, sort_by_date]
if (rules.every(rule => rule === "true")) {
// do something
}
uj5u.com熱心網友回復:
如果您只想為 API 限制一個過濾器,我認為此解決方案可以:
const filterWeeklyTrending = (unfilteredResults) => {/*...*/}
// rest of the possible filter functions...
const filterFunctions = {
weekly_trending: filterWeeklyTrending,
monthly_trending: filterMonthlyTrending,
// rest of the possible filters...
}
// Suppose you are using Express and queries live in `req.param` like so:
// { weekly_trending: 1 }
// We want to return an array of matched filter names here.
const matchedFilterNames = Object.keys(filterFunctions).filter(key => key in req.param) // e.g. ['weekly_trending']
if (matchedFilterNames.length !== 1) {
// tell client they must provide only 1 filter
return
}
// otherwise, filter results
const selectedFilterFunction = filterFunctions[matchedFilterNames[0]]
const filteredResults = selectedFilterFunction(unfilteredResults)
但是,如果您正在構建 API,并且過濾器由最終用戶指定,那么強制最終用戶從一開始就只能選擇一個過濾器的稍微不同的設計會緩解問題嗎?
例如,如果它是一個 HTTP API,它會更好地向用戶表明只提供一個過濾器選項,而不是http://my.site/api/sports?weekly_trending=true我們有http://my.site/api/sports?sort=weekly_trending?
然后我們可以替換以下內容:
const matchedFilterNames = Object.keys(filterFunctions).filter(key => key in req.param) // e.g. ['weekly_trending']
if (matchedFilterNames.length !== 1) {
// tell client they must provide only 1 filter
return
}
和
const filterName = req.params.sort // if this is where user specifies the filter function
if (!(filterName in filterFunctions)) {
// tell client this filter does not exist
return
}
uj5u.com熱心網友回復:
在示例中,該函式flagFilter()采用兩個 @param:
- 第一個 @param 是一個標志陣列(布林值)
- 第二個 @param 是一個標志,如果忽略默認為
false. 如果true通過,則陣列將使用.some()陣列方法運行。.some()將查看標志是否為true. 一旦找到它是第一個true,它就會退出并回傳,true否則它將回傳false。如果false通過,則.every()使用陣列方法。.every()要求每個標志都是,true否則它將回傳false。
詳細資訊在下面的示例中注釋
// Utility function
const log = data => console.log(JSON.stringify(data));
// Define flags (note: Booleans are not quoted
const weekly = false, monthly = false, quarterly = false, likes = true, date = false;
// Define an array of the flags
const flags = [weekly, monthly, quarterly, likes, date];
/**
* Iterate through a given array of
* Booleans and see if all or at least
* one is true.
* @param {array<boolean>} array - An
* array of booleans
* @param {boolean} mode - (@default false)
* if true then only one true flag is
* needed otherwise all flags need to
* be true.
* @returns {boolean}
*/
const flagFilter = (array, mode = false) => mode == true ? array.some(f => f) : array.every(f => f);
// Needs all flags to be true
log(flagFilter(flags));
// Needs only one flag to be true
log(flagFilter(flags, true));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/446728.html
標籤:javascript
