为什么此递归函数覆盖第二个调用的值?

时间:2019-03-02 09:23:56

标签: javascript reactjs ecmascript-6 functional-programming

对不起,标题,我什至不知道该如何表达这里发生的事情。

我正在React中开发一种费用跟踪程序,该程序支持多种货币。可以将所跟踪的费用任意嵌套在JSON对象中。

entertainment: {
  _values: {
    USD: 23,
    AUD: 5,
  },
  'food & drink': {
    _values: {
      AUD: 83,
    },
    'local bar': {
      _values: {
        AUD: 28,
        USD: 2,
      },
    },
  },
  minigolf: {
    _values: {
      USD: 112,
    },
  }
}

费用可以直接存储在其中,但也可以作为进一步详细子费用的“父项”类别。

要显示费用的总值,我编写了两个函数: sumValues(values) 总结_values个对象的数组(值对象是货币代码和整数的键值存储)

totalExpense(expense) 返回费用的总值。即它拥有的任何_values,再加上所有子项支出的totalExpense。

我以为我将它们写为纯函数,但是当递归调用totalExpense()时,费用的第一个孩子返回错误的总数。

totalExpense(entertainment);
//-> Object { USD: 137, AUD: 116 }

totalExpense(entertainment['food & drink']);
//-> Object { AUD: 111, USD: 2 }

totalExpense(entertainment);
totalExpense(entertainment['food & drink']);
//-> Object { AUD: 139, USD: 4 }

不好

我已经花了几个小时在看这段代码,但是我一生都看不到发生了什么事

  sumValues = values => {
    return values.reduce((acc, cur) => {
      for (const currency in cur) {
        acc[currency]
          ? (acc[currency] = acc[currency] + cur[currency])
          : (acc[currency] = cur[currency]);
      }
      return acc;
    });
  };
  totalExpense = expense => {
    const values = [];

    if (expense['_values']) {
      values.push(expense['_values']);
    }

    const subExpenses = Object.keys(expense).filter(child => {
      return child[0] !== '_';
    });

    if (subExpenses.length > 0) {
      for (const subExpense of subExpenses) {
        let subtotal = this.totalExpense(expense[subExpense]);
        values.push(subtotal);
      }
    }

    if (values.length) {
      return this.sumValues(values);
    } else {
      throw Error('No values in this expense');
    }
  };
  render() {
    const entertainment = {
      _values: {
        USD: 23,
        AUD: 5,
      },
      'food & drink': {
        _values: {
          AUD: 83,
        },
        'local bar': {
          _values: {
            AUD: 28,
            USD: 2,
          },
        },
      },
      minigolf: {
        _values: {
          USD: 112,
        },
      },
    };

    console.log(this.totalExpense(entertainment));
    console.log(this.totalExpense(entertainment['food & drink']));
    console.log(this.totalExpense(entertainment['minigolf']));

    return;
  }

1 个答案:

答案 0 :(得分:1)

问题是您的reduce回调的初始值是values数组中的第一项,然后您继续分配给该项:

    acc[currency]
      ? (acc[currency] = acc[currency] + cur[currency])
      : (acc[currency] = cur[currency]);

因此,每次调用sumValues时,第一项都会发生变异。而是提供一个空对象作为reduce的初始值:

 sumValues = values => {
    return values.reduce((acc, cur) => {
      for (const currency in cur) {
        acc[currency]
          ? (acc[currency] = acc[currency] + cur[currency])
          : (acc[currency] = cur[currency]);
      }
      return acc;
    }, {});
  };

sumValues = values => {
  return values.reduce((acc, cur) => {
    for (const currency in cur) {
      acc[currency] ?
        (acc[currency] = acc[currency] + cur[currency]) :
        (acc[currency] = cur[currency]);
    }
    return acc;
  }, {});
};
totalExpense = expense => {
  const values = [];

  if (expense['_values']) {
    values.push(expense['_values']);
  }

  const subExpenses = Object.keys(expense).filter(child => {
    return child[0] !== '_';
  });

  if (subExpenses.length > 0) {
    for (const subExpense of subExpenses) {
      let subtotal = this.totalExpense(expense[subExpense]);
      values.push(subtotal);
    }
  }
  if (values.length) {
    return this.sumValues(values);
  } else {
    throw Error('No values in this expense');
  }
};
const entertainment = {
  _values: {
    USD: 23,
    AUD: 5,
  },
  'food & drink': {
    _values: {
      AUD: 83,
    },
    'local bar': {
      _values: {
        AUD: 28,
        USD: 2,
      },
    },
  },
  minigolf: {
    _values: {
      USD: 112,
    },
  },
};

console.log(totalExpense(entertainment));
console.log(totalExpense(entertainment['food & drink']));