Have problem with function reduce in JS / Возникла проблема с работой метода reduce в JavaScript

When using the reduce method in the following code, undefined is thrown on the second loop through the prev variable. As a result, the function does not return the sum of the areas of all triangles. What could be the problem with reduce?

При использовании метода reduce в следующем коде возникает undefined при втором проходе цикле в переменной prev. Как результат функция не выдает сумму площадей всех треугольников. В чем может быть проблема с reduce?

class GeometricFigure {
  getArea() {
    return 0
  }
  toString() {
    return Object.getPrototypeOf(this).constructor.name
  }
}

class Triangle extends GeometricFigure {
  constructor(a, b, c) {
    super()
    this.a = a
    this.b = b
    this.c = c
  }

  getArea() {
    let p = (this.a + this.b + this.c) * 0.5
    let S = Math.sqrt(p * (p - this.a) * (p - this.b) * (p - this.c))
    return S
  }

  toString() {
    return Object.getPrototypeOf(this).constructor.name
  }
}

function handleFigures(figures) {
  let totalArea = figures.reduce((prev, current) => {
    if (current instanceof GeometricFigure) {
      console.log(prev)
      console.log(current['getArea']())
      prev + current['getArea']()
      console.log(
        `${Object.getPrototypeOf(current)}: ${current[
          'toString'
        ]()} - area: ${current['getArea']()}`
      )
    } else throw new Error('Current object is not instance of GeometricFigure')
  }, 0)
  return totalArea
}

const figures = [new Triangle(4, 5, 3), new Triangle(3, 6, 6.71), new Triangle(6, 4, 7.21)]
console.log(handleFigures(figures))


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

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

Проблема в том, что из Вашей стрелочной функции следует что-то возвращать.

return prev + current['getArea'](); // !!!

class GeometricFigure {
  getArea() {
    return 0
  }
  toString() {
    return Object.getPrototypeOf(this).constructor.name
  }
}

class Triangle extends GeometricFigure {
  constructor(a, b, c) {
    super()
    this.a = a
    this.b = b
    this.c = c
  }

  getArea() {
    let p = (this.a + this.b + this.c) * 0.5
    let S = Math.sqrt(p * (p - this.a) * (p - this.b) * (p - this.c))
    return S
  }

  toString() {
    return Object.getPrototypeOf(this).constructor.name
  }
}

function handleFigures(figures) {
  let totalArea = figures.reduce((prev, current) => {
    if (current instanceof GeometricFigure) {
      console.log(prev)
      console.log(current['getArea']())
      console.log(
        `${Object.getPrototypeOf(current)}: ${current[
          'toString'
        ]()} - area: ${current['getArea']()}`
      )
      return prev + current['getArea']();
    } else throw new Error('Current object is not instance of GeometricFigure')
  }, 0)
  return totalArea
}

const figures = [new Triangle(4, 5, 3), new Triangle(3, 6, 6.71), new Triangle(6, 4, 7.21)]
console.log(handleFigures(figures))

→ Ссылка