0

I don't know why but I always receive an error when I run the following code:

function list(names) {
  let str = '';
  if (!names) {
    return ''
  } else if (names.length == 2) {
    return names[0].name + ' & ' + names[1].name;
  } else if (names.length == 1) {
    return names[0].name;
  } else {
    for (i = 0; i < (names.length - 2); i++) {
      str += names[i].name + ', ';
    }

    str += names[names.length - 2].name + ' & ' + names[names.length - 1].name;
    return str;
  }
}

with test cases in codewars kata. The error is:

TypeError: Cannot read property 'name' of undefined
    at list
    at /home/codewarrior/index.js:36:19
    at /runner/frameworks/javascript/cw-2.js:152:11
    at Promise._execute

names should be an array which can be empty and the array elements are objects with name properties.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Jithin
  • 169
  • 9

2 Answers2

0

As an alternate solution, you can do with map, lastIndexOf and slice.

You have to encounter 2 corner cases:

1) An input array of zero-length then you've to return empty string as

 if (!names.length) return "";

2) An input array of length one, then you have to just return the name as:

if (names.length === 1) return names[0].name;

function list(names) {
  if (!names.length) return "";
  if (names.length === 1) return names[0].name;
  const namesStr = names.map((o) => o.name).join(", ");
  const index = namesStr.lastIndexOf(",");
  const result = namesStr.slice(0, index) + " &" + namesStr.slice(index + 1);
  return result;
}

const result = list([{ name: "Bart" }, { name: "Lisa" }, { name: "Maggie" }]);
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

The kata mentions that you should return an empty string for an empty array. I think you intended to do that with

if (!names) {
    return ''
  }

... but an empty array is still truthy. Perhaps that line should be if (!names.length).

Andy Bonner
  • 128
  • 1
  • 6
  • Btw, it's considered best practice in javascript to use strict comparison in evaluations, like `.length === 1`, since, e.g., `true == 1` is true – Andy Bonner Jun 21 '21 at 15:29