TypeError: Cannot read property 'includes' of undefined (line 29 in function PGroup.has)

Вот код класса:

class PGroup {
  // Your code here
  constructor(members) {
    this.empty = members;
  }

  add(value) {
    if (this.has(value)) {
      return this;
    }
    return new PGroup(this.empty.concat[value]);
  }

  /*
                Its add method, however, should return a new PGroup instance with the given member added and leave the old one unchanged.
                Similarly, delete creates a new instance without a given member.
            */


  delete(value) {
    if (!this.has(value)) {
      return this;
    }
    this.empty = this.empty.filter((v) => v != value)
    return new PGroup(this.empty);
  }

  has(value) {
    return this.empty.includes(value);
  }

  static from(arr) {
    let gr = new Group();
    for (let i of arr) {
      gr.add(i);
    }
    return gr;
  }
}

PGroup.empty = new PGroup([]);
let a = PGroup.empty.add("a");
let ab = a.add("b");
let b = ab.delete("a");

console.log(b.has("b"));
// → true
console.log(a.has("b"));
// → false
console.log(b.has("a"));
// → false

Код ошибки:

TypeError: Cannot read property 'includes' of undefined (line 29 in function PGroup.has) 
 called from line 8 in function PGroup.add
 called from line 44 in function eval

Ответы (1 шт):

Автор решения: Grundy

Проблема заключается в методе .add.

Метод .concat – это функция, в данном же случае

this.empty.concat[value]

Вместо вызова функции идет попытка получить значение свойства. Как результат, в большинстве случаев будет undefined.

Для решения достаточно заменить эту часть на вызов функции

this.empty.concat(value)

Пример, когда код мог работать:

class PGroup {
  // Your code here
  constructor(members) {
    this.empty = members;
  }

  add(value) {
    if (this.has(value)) {
      return this;
    }
    return new PGroup(this.empty.concat[value]);
  }

  /*
                Its add method, however, should return a new PGroup instance with the given member added and leave the old one unchanged.
                Similarly, delete creates a new instance without a given member.
            */


  delete(value) {
    if (!this.has(value)) {
      return this;
    }
    this.empty = this.empty.filter((v) => v != value)
    return new PGroup(this.empty);
  }

  has(value) {
    return this.empty.includes(value);
  }

  static from(arr) {
    let gr = new Group();
    for (let i of arr) {
      gr.add(i);
    }
    return gr;
  }
}

PGroup.empty = new PGroup([]);
let a = PGroup.empty.add("name");

console.log(a.has("a"));
// → false
console.log(a.has("n"));
// → false

→ Ссылка