如何防止突变

发布于 2025-02-13 06:56:18 字数 2126 浏览 0 评论 0原文

我一直在尝试编写一个计算混合账单的函数,而没有使用ES6的突变。
我在下面有一个代码,它的作用是,它需要一组人的钱,添加了所有代码,以获取总金额,然后循环,然后分配给用户的长度,以获取多少钱人。然后,我从用户数量中减去每人份额,因此列表包含负/正值或0,具体取决于它们贡献了多少总账单。然后,为了提取负数和阳性数量的人来说,使用大于0且小于0的人的用户过滤器。

到目前为止,代码正常运行,并且按照我的预期运行良好,但是我使用的是不断变化的变量,从我的理解中导致突变,是否有其他方法可以防止此代码中的突变,

您可以查看代码在摘要上

const users = [
  { id: 1, username: "John One", amount: 50 },
  { id: 2, username: "John Two", amount: 75 },
  { id: 3, username: "John Three", amount: 100 },
  { id: 4, username: "John Four", amount: 125 },
  { id: 5, username: "John five", amount: 150 },
  { id: 6, username: "John six", amount: 50 },
  { id: 7, username: "John seven", amount: 150 },
  { id: 8, username: "John eight", amount: 250 },
  { id: 9, username: "John nine", amount: 150 },
  { id: 10, username: "John Ten", amount: 100 },
]


const total = users.reduce((acc, user) => acc + user.amount, 0);
const perPersonShare = total / users.length;
const sortedUsers = users.map((user) => { return { ...user, amount: user.amount - perPersonShare, hasToPay: [] } });
const negativeAmount = sortedUsers.filter(user => user.amount < 0);
const positiveAmount = sortedUsers.filter(user => user.amount > 0);


const res = positiveAmount.reduce((acc, user) => {

  let balance = user.amount;

  return acc.map((ower) => {

    if (ower.amount === 0 || balance === 0) return ower;

    if (balance <= Math.abs(ower.amount)) {
      const updated = {
        ...ower,
        hasToPay: [...ower.hasToPay, { to: user.username, amount: balance }],
        amount: ower.amount + balance,
      };

      balance = 0;
      return updated;
    }

    if (balance >= Math.abs(ower.amount)) {
      const updated = {
        ...ower,
        hasToPay: [...ower.hasToPay, { to: user.username, amount: Math.abs(ower.amount) }],
        amount: 0,
      };

      balance = balance + ower.amount;
      return updated;
    }

    return ower;

  });


}, negativeAmount);

console.log(JSON.stringify(res, 0, 2))
console.log(perPersonShare);
console.log(total);

I have been trying to write a function which calculates mixed bills, with NO MUTATION using ES6.
I have a code below, what it does is, it takes group of people's given money, adds all of them in order to get the total amount and then loops and then divides to length of the users in order to get how much it comes to per person. And then I'm subtracting per-person share from users amount, so list contains either negative/positive or 0, depending how much they have contributed into total bill. Then goes filters of users for people who have greater than 0 and less than 0 in order to extract negative and positive amounts.

So far the code works fine and the output as I expected, however I'm using let variable which is constantly changing, which leads to mutation from my understanding, is there any other way of preventing mutation in this code,

You can view the code on snippet

const users = [
  { id: 1, username: "John One", amount: 50 },
  { id: 2, username: "John Two", amount: 75 },
  { id: 3, username: "John Three", amount: 100 },
  { id: 4, username: "John Four", amount: 125 },
  { id: 5, username: "John five", amount: 150 },
  { id: 6, username: "John six", amount: 50 },
  { id: 7, username: "John seven", amount: 150 },
  { id: 8, username: "John eight", amount: 250 },
  { id: 9, username: "John nine", amount: 150 },
  { id: 10, username: "John Ten", amount: 100 },
]


const total = users.reduce((acc, user) => acc + user.amount, 0);
const perPersonShare = total / users.length;
const sortedUsers = users.map((user) => { return { ...user, amount: user.amount - perPersonShare, hasToPay: [] } });
const negativeAmount = sortedUsers.filter(user => user.amount < 0);
const positiveAmount = sortedUsers.filter(user => user.amount > 0);


const res = positiveAmount.reduce((acc, user) => {

  let balance = user.amount;

  return acc.map((ower) => {

    if (ower.amount === 0 || balance === 0) return ower;

    if (balance <= Math.abs(ower.amount)) {
      const updated = {
        ...ower,
        hasToPay: [...ower.hasToPay, { to: user.username, amount: balance }],
        amount: ower.amount + balance,
      };

      balance = 0;
      return updated;
    }

    if (balance >= Math.abs(ower.amount)) {
      const updated = {
        ...ower,
        hasToPay: [...ower.hasToPay, { to: user.username, amount: Math.abs(ower.amount) }],
        amount: 0,
      };

      balance = balance + ower.amount;
      return updated;
    }

    return ower;

  });


}, negativeAmount);

console.log(JSON.stringify(res, 0, 2))
console.log(perPersonShare);
console.log(total);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最丧也最甜 2025-02-20 06:56:18

我是新手的,所以我的答案可能有效,但是您可以使用object.freeze()冻结对象,而是使用数组来定义用户,而是可以使用对象定义它们。 It is from my understanding

here is some links I found they might be useful to you

https://medium.com/@fknussel/arrays-Arrays-abigns-and-mutations-6b23348b54aahttps://medium.comnyum.com/@fknussel/arrays-brays-objects-mutations-mutations-mutations-mutations-mutations-mutations-mutations-mutations-mutations-mutations-mutations-mutions-and-mutations-and-mutations-and-mutiations-mutim-6b2348b54aaaa

I'm new to this so my answer may work or not, but You can use Object.freeze() to freeze the object but instead of using arrays to define users you can define them using objects. It is from my understanding

here is some links I found they might be useful to you

https://roclv.gitbooks.io/redux-getting-started/content/09.redux-avoiding-array-mutations-with-concat-slice-and-spread.html

https://medium.com/@fknussel/arrays-objects-and-mutations-6b23348b54aahttps://medium.com/@fknussel/arrays-objects-and-mutations-6b23348b54aa

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文