gpt4 book ai didi

javascript - 用于探索大量真/假属性的优雅解决方案

转载 作者:行者123 更新时间:2023-11-29 16:36:16 26 4
gpt4 key购买 nike

这是一个非常普遍的问题,但我的具体用例是基于包含 true/false 设置的对象构建一个“友好”的过滤器名称。

这是这些设置对象之一的示例

var settings = {
includeMen: true,
includeWomen: false,
includeDependents: true,
}

业余解决方案是一大组 if 语句,例如

if(settings.includeMen && settings.includeWomen && settings.includeDependents){
return "All People"
}

if(settings.includeMen && !settings.includeWomen && settings.includeDependents){
return "Men and Children"
}

if(settings.includeMen && settings.includeWomen && !settings.includeDependents){
return "Men and Women"
}
...

还有什么不那么业余的想法吗?(如果有帮助的话,项目正在使用 Lodash)

最佳答案

 const {includeMen, includeWomen, includeDependents} = settings;

const result = [];
if(includeMen) result.push("Men");
if(includeWomen) result.push("Women");
if(includeDependents) result.push("Children");

if(result.length === 3)
return "All people";
if(!result.length)
return "No one";

return result.join(" and ");

如果您想为每种情况提供自定义输出,您可以进行一些有趣的位移:

const {includeMen, includeWomen, includeDependents} = settings;

return [
"No one",
"Children",
"Women",
"Children and Women",
"Men",
"Men and Children",
"Men and Women",
"All people"
][+includeDependents + (includeWomen << 1) + (includeMen << 2)];

(免责声明:如果你这样做,你的队友会恨你:))

关于javascript - 用于探索大量真/假属性的优雅解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51254413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com