-1

I'm doing groupBy function which will accept a callback and return an object with grouped values. If no callback is passed, the method must group by array values.

I've done it, but eslint does't accept it, any suggestions, how to refactor it?

Array.prototype.groupBy = function groupBy(callback) {
    if (!callback) {
      return this.reduce((acc, x) => 
        (acc[(x)] ? acc[(x)].push(x) : acc[(x)] = [x], acc), {});
    }

    return this.reduce((acc, x) => {
      const key = callback(x);

      if (!acc[key]) {
        return {
          ...acc,
          [key]: [x],
        };
      }

      return {
        ...acc,
        [key]: [...acc[key], x],
      };
    }, {});
  };
}

And eslint errors are :

  1. 3:26 Arrow function should not return assignment. eslint(no-return-assign)
  2. 4:54 Unexpected use of comma operator. eslint(no-sequences)
  • See [How to deal with Unexpected use of comma operator no-sequences EsLINT warning](/q/64102173/4642212) — _“Write the \[part before the comma\] on its own line.”_ — and [What is the practice of multiple expressions in an arrow function without curly brackets](/q/48973691/4642212). The [rule description](//eslint.org/docs/rules/no-sequences) and the [documentation for the comma operator](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) describe how to avoid it and what it is equivalent to. – Sebastian Simon May 12 '21 at 09:28

1 Answers1

-1

Array.prototype.groupBy = function groupBy(callback) {
  if (!callback) {
    return this.reduce((acc, x) => {
      acc[(x)] ? acc[(x)].push(x) : acc[(x)] = [x];
      return acc;
    }, {})
  }

  return this.reduce((acc, x) => {
    const key = callback(x);

    if (!acc[key]) {
      return {
        ...acc,
        [key]: [x],
      };
    }

    return {
      ...acc,
      [key]: [...acc[key], x],
    };
  }, {});
};
}
bel3atar
  • 913
  • 4
  • 6