2

Let's say that we have an array like this:

let list = [
  {
    name: '1',
    count: 0,
  },
  {
    name: '2',
    count: 10,
  },
  {
    name: '3',
    count: 18,
  },
];

Then how to update all items to increase count by 1?

Here comes several solutions, while none of them is quite satisfactory:

/* no-restricted-syntax error, pass */
for (const item of list) {
  item.count += 1;
}


/* no-param-reassign error, pass */
list.forEach((item) => {
  item.count += 1;
});


/* 
  Object.assign is free to use without error
  but it against the intention of no-param-reassign
 */
list.forEach((item) => {
  Object.assign(item, { count: item.count + 1 });
});


/* 
  use Array.map() to replace the original array
  but it costs a lot when the item is large or the array has a large length
  also ugly code for such a tiny update
 */
list = list.map((item) => ({
  ...item,
  count: item.count + 1,
}));

If you have a better solution or consider Array.map() is good enough, please leave your opinion.

Thank you :)

  • 1
    why not? list = list.map(item => item.count++) – Diego D Mar 30 '22 at 14:29
  • Are the rules such as `no-param-reassign` strict or personal preference? Because it sounds like you are trying to do just that. If strict, seems like `Array.map()` is the best solution. – mykaf Mar 30 '22 at 14:37
  • @user1599011 It's strict. I want to improve my code style by a authoritative style guide (and I choose Airbnb JavaScript Style). It's helpful in most condition, but I think sometimes it's over-optimized. – Seaside Lee Mar 30 '22 at 14:46

1 Answers1

2

I generally use normal for loop to avoid Airbnb lint issue as follow:

for (let index = 0; index < list.lenght; index++) {
    const item = list[index];
    if (item) {
        item.count += 1;
    }
}
Ashok
  • 2,411
  • 1
  • 13
  • 23
  • Wouldn't that still break the "no-param-reassign" rule? – mykaf Mar 30 '22 at 14:52
  • 1
    No, `no-param-reassign` rule only mentions that you cannot update the object/value passed as a function parameter, like in `forEach` function the item is a function parameter. Since here we are not using any function, we are not breaking `no-param-reassign` rule. – Ashok Mar 30 '22 at 14:53
  • Gotcha! And in that case, this is the simplest, most straightforward choice. – mykaf Mar 30 '22 at 14:57
  • Yes, simplest and straightforward, this is good for me. While I'm considering whether to overwrite `no-restricted-syntax` rule for this issue https://github.com/airbnb/javascript/issues/2428 – Seaside Lee Mar 30 '22 at 15:09
  • I submit an new issue about this problem and get some suggestions https://github.com/airbnb/javascript/issues/2585 – Seaside Lee Apr 01 '22 at 06:40
  • Doesn't this break the unary increment prohibition? – Noah Oct 02 '22 at 07:29