【发布时间】:2019-07-24 05:13:35
【问题描述】:
对不起标题,我什至不知道如何表达这里发生的事情。
我正在开发一个支持多种货币的 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(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;
}
【问题讨论】:
-
没有 JSON 对象 这样的东西。 JSON 总是 一个字符串。
标签: javascript reactjs ecmascript-6 functional-programming