JavaScript Algorithm - Code review and correction

var data = [[18, 20],[45, 2],[61, 12],[37, 6],[21, 21],[78, 9]]; //input
 
function openOrSenior(data){
   data.map(function (x) {
        return (x[0]>=55 && x[1]>7)?'Senior':'Open';
   });
 }
openOrSenior(data);

Can somebody please correct me here?
Why did somebody use closure in the following example?
Above mentioned is my code and following is the best approach.

function openOrSenior(data){
  function determineMembership(member){
    return (member[0] >= 55 && member[1] > 7) ? 'Senior' : 'Open';
  }
  return data.map(determineMembership);
}

Following is the output.

Output : ["Open", "Open", "Senior", "Open", "Open", "Senior"]

Maybe because the second example is more descriptive? The inner function described what it does, and the parameter is better named (rather than naming it x).

I think people might prefer either one. But you can also combine them like this:

function openOrSenior(data){
  data.map(function determineMembership(member) {
    return (member[0] >= 55 && member[1] > 7) ? 'Senior' : 'Open';
  });
 }

Let me be clear with two things. First example does not do anything because map() doesn’t mutate array; it returns new array with modified elements. Second example is not using closure in any way; it is a nested function but nothing more.

Disregarding the mistakes, the first and second example is identical in terms of functionality. However, the second example is better because it clarifies what the callback function for map() does. In first example, I need to read the content of anonymous callback to understand what it is doing. In second example, I can simply read the name of the callback and trust the programmer who wrote it.

1 Like