Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to satisfy the lint rules 'array-callback-return'?

This is my first cut:

const planLimits = {plan1: {condition1: 50, ...}}

function initialisePlanLimits(planLimits) {
  const limits = new Map();
  Object.keys(planLimits).map((planId) => (
    const limitMap = new Map(Object.entries(planLimits[planId]));
    limits.set(planId, limitMap);
  ));
  return limits;
}

The linter flags this error: error Expected to return a value in this function array-callback-return

So I changed to this version:

function initialisePlanLimits(planLimits) {
  const limits = new Map();
  Object.keys(planLimits).map((planId) => (
    limits.set(planId, new Map(Object.entries(planLimits[planId])))
  ));
  return limits;
}

It throws another error Unexpected parentheses around single function argument having a body with no curly braces arrow-parens

My questions:

1) I reckon I can fix my first version by sticking in a return null within the curry bracket. But is there a better, more elegant way? A bogus return statement does not make sense in this context

2) Why the second version fails? Isn't it equivalent to the first version?

like image 563
Anthony Kong Avatar asked Mar 25 '17 22:03

Anthony Kong


People also ask

Can we return in callback function?

A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value. Yes, it makes fun sense to try and return a value from a promise callback.

What is return callback?

Return statements are used to indicates the end of a given function's execution whereas callbacks are used to indicate the desired end of a given function's execution.


2 Answers

If I use forEach instead of map, it will not cause the array-callback-return lint error

 Object.keys(planLimits).forEach((planId) => (
    const limitMap = new Map(Object.entries(planLimits[planId]));
    limits.set(planId, limitMap);
  ));
like image 172
Anthony Kong Avatar answered Sep 30 '22 06:09

Anthony Kong


Well, accepted answer advocates about using 'forEach,' which is true. Please read below explaination from ESLint documentation,

Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it's probably a mistake. If you don't want to use a return or don't need the returned results, consider using .forEach instead.

like image 27
Gaurang Patel Avatar answered Sep 30 '22 05:09

Gaurang Patel