gpt4 book ai didi

javascript - 有什么办法可以缩短这段代码吗?

转载 作者:行者123 更新时间:2023-12-05 09:33:03 24 4
gpt4 key购买 nike

所以我有一个评级系统,我已经编写了以下代码来显示要显示的星星数量,尽管它很长,所以我正在尝试找到一种方法来缩短它。

我不知道是否有某种算法先相乘然后加上空星之类的?

const rating = (recipe) => {
const value = (recipe.rating / recipe.votes.length).toFixed(1);
if (value >= 4.9)
return (
<>
<FaStar />
<FaStar />
<FaStar />
<FaStar />
<FaStar />
</>
);
if (value >= 4.5)
return (
<>
<FaStar />
<FaStar />
<FaStar />
<FaStar />
<FaStarHalfAlt />
</>
);
if (value >= 4)
return (
<>
<FaStar />
<FaStar />
<FaStar />
<FaStar />
<FaRegStar />
</>
);
if (value >= 3.5)
return (
<>
<FaStar />
<FaStar />
<FaStar />
<FaStarHalfAlt />
<FaRegStar />
</>
);
if (value >= 3)
return (
<>
<FaStar />
<FaStar />
<FaStar />
<FaRegStar />
<FaRegStar />
</>
);
if (value >= 2.5)
return (
<>
<FaStar />
<FaStar />
<FaStarHalfAlt />
<FaRegStar />
<FaRegStar />
</>
);
if (value >= 2)
return (
<>
<FaStar />
<FaStar />
<FaRegStar />
<FaRegStar />
<FaRegStar />
</>
);
if (value >= 1.5)
return (
<>
<FaStar />
<FaStarHalfAlt />
<FaRegStar />
<FaRegStar />
<FaRegStar />
</>
);
if (value >= 1)
return (
<>
<FaStar />
<FaRegStar />
<FaRegStar />
<FaRegStar />
<FaRegStar />
</>
);
if (value >= 0.5)
return (
<>
<FaStarHalfAlt />
<FaRegStar />
<FaRegStar />
<FaRegStar />
<FaRegStar />
</>
);
return (
<>
<FaRegStar />
<FaRegStar />
<FaRegStar />
<FaRegStar />
<FaRegStar />
</>
);
};

最佳答案

如果你真的想缩短它:

const rating = (recipe) => {
const value = (recipe.rating / recipe.votes.length).toFixed(1);

const stars = Array.from(Array(5)).map(() => <FaRegStar/>);

if (value >= 4.9) {
return stars.map(() => <FaStar/>);
}

for (let i = 0; i < Math.round(value); i++) {
stars[i] = i > value - 1 ? <FaStarHalfAt/> : <FaStar/>;
}

return stars;
};

这样会更容易理解(评分 >= 4.9 时会显示 5 星):

const rating = (recipe) => {
let value = (recipe.rating / recipe.votes.length).toFixed(1);

if (value >= 4.9) {
return Array.from(Array(5)).map(() => <FaStar/>);
}

const stars = [];
while (value >= 1) {
stars.push(<FaStar/>);
value--;
}

if (value >= 0.5) {
stars.push(<FaStarHalfAt/>);
}

while (stars.length < 5) {
stars.push(<FaRegStar/>);
}

return stars;
};

或者更短一点但仍然可以理解:

const rating = (recipe) => {
let value = (recipe.rating / recipe.votes.length).toFixed(1);

if (value >= 4.9) {
return Array.from(Array(5)).map(() => <FaStar/>);
}

const stars = [];
while (stars.length < 5) {
stars.push(value >= 1
? <FaStar/>
: value >= 0.5
? <FaStarHalfAt/>
: <FaRegStar/>);
value--;
}

return stars;
};

关于javascript - 有什么办法可以缩短这段代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67547898/

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