Using ESLint with Airbnb rules, I can't get a reduce method with comparison operator to work.
In the code below, the array named data holds objects, each with a property named id. The error messages ESLint throws are:
const maxId = data.reduce((prev, current) => {
return prev.id > current.id ? prev.id : current.id;
});
ESLint Error: arrow-body-style / Unexpected block statement surrounding arrow body.
const maxId = data.reduce((prev, current) =>
prev.id > current.id ? prev.id : current.id);
ESLint Error: no-confusing-arrow / Arrow function used ambiguously with a conditional expression.
const maxId = data.reduce(function (prev, current) {
return prev.id > current.id ? prev.id : current.id;
});
ESLint Error: prefer-arrow-callback / Unexpected function expression.
So how can I get this to work?
Arrow functions cannot be used to write object methods because, as you have found, since arrow functions close over the this of the lexically enclosing context, the this within the arrow is the one that was current where you defined the object.
In short, with arrow functions there are no binding of this . In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions the this keyword always represents the object that defined the arrow function.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .
Wrap the body in parenthesis to make it not "confusing":
(prev, current) => (prev.id > current.id ? prev.id : current.id)
@Felix has the solution to fix the linter problems, but to make your script work functionally you should use
const maxId = data.reduce((prev, current) => Math.max(prev, current.id), -Infinity);
// ^^^^ ^^^^^^^^^^^
that will work on data
arrays of sizes other than 1 and 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With