我需要根据某些条件返回true或false,我没有得到更干净的代码来执行此操作:
我需要根据这个条件在UI上隐藏或显示一些元素,这些元素应该返回true或false:
scope.isDataEnabled =function(options){ //Here if supppose a comes,
// then i need to send true, otherwise false
if(!$rootScope.currentProduct.id ==
ProductConstants.BB_PRODUCT_ID){
return true;
}
else{
_.map( $rootScope.currentUser.permissions, permissionObj =>{
// permissions is an Array
return (permissionObj.module == "DATA" &&
permissionObj.values == "b" && options=="a") //need to send true
//if this condition satisfies
});
}
return false; //after returning true,
//it comes to this line and sets to false
}
请帮我指导,我应该使用什么来实现它。我曾想过使用三元运算符,但不知道如何在地图中使用它。
将代码简化为可以操作的最小测试场景(只使用普通的旧ES20xx(可能会有所帮助。类似于:
let $rootScope = {
currentProduct: {
id: `x`
},
currentUser: {
permissions: [{
module: `BB_DATASET`,
values: `b`
}, {
module: `some`,
values: `a`
}]
}
};
const ProductConstants = {
BB_PRODUCT_ID: `y`
}
console.log(testMe(`a`)); // true (currentProduct.id not BB_PRODUCT_ID)
ProductConstants.BB_PRODUCT_ID = `x`;
console.log(testMe(`a`)); // true (module && values && options)
$rootScope.currentUser.permissions[0].module = `AA_DATASET`;
console.log(testMe(`a`)); // false (module not BB_DATASET)
$rootScope.currentUser.permissions[0].module = `BB_DATASET`;
console.log(testMe(`b`)); // false (options not `a`)
$rootScope.currentUser.permissions[0].values = `c`;
console.log(testMe(`a`)); // false (values not `b`)
function testMe(options) {
if ($rootScope.currentProduct.id !== ProductConstants.BB_PRODUCT_ID) {
return true;
}
const found = $rootScope.currentUser.permissions.find( v =>
v.module === `BB_DATASET` &&
v.values === `b` &&
options == `a`);
return found ? true : false;
}
.as-console-wrapper {
top: 0;
max-height: 100% !important;
}
首先,map函数内部的返回不会将值返回到外部函数,您只是将结果返回到map函数本身。map函数的结果永远不会返回。
此外,我认为您可能希望使用_.some
而不是map。map
用于转换数据,而some
用于检查某个条件是否匹配。
return _.some($rootScope.currentUser.permissions, permissionObj => {
return (permissionObj.module == "BB_DATASET"
&& permissionObj.values == "b"
&& options=="a")
});
这将检查任何权限是否与给定条件匹配。或者,如果希望所有内容都符合条件,也可以使用_.all
。