实现说明
逻辑集中在函数 unpaidTotals里。
返回值是携带 length、sum、cents 的对象。
常见问题
unpaidTotals 会修改传入的参数吗?
不会修改。入参只读,返回值是全新构造的。
它依赖第三方库吗?
没有引用任何第三方库,标准库就够了。 文件在加载时定义 unpaidTotals。
入口签名:function unpaidTotals(invoices)
核心语句
const open = invoices.filter((invoice) => !invoice.paid);
代码示例
/**
* @typedef {Object} Invoice
* @property {string} id
* @property {number} cents — integer cents only, never floats
* @property {boolean} paid
*/
/**
* Totals the unpaid invoices; money stays in integer cents.
* @param {Invoice[]} invoices
* @returns {{ open: number, openCents: number }}
*/
function unpaidTotals(invoices) {
const open = invoices.filter((invoice) => !invoice.paid);
return {
open: open.length,
openCents: open.reduce((sum, invoice) => sum + invoice.cents, 0),
};
}
/** @type {Invoice[]} */
const invoices = [
{ id: 'inv-1', cents: 4950, paid: true },
{ id: 'inv-2', cents: 1200, paid: false },
{ id: 'inv-3', cents: 830, paid: false },
];
const totals = unpaidTotals(invoices);
console.log(`open invoices: ${totals.open}`);
console.log(`open cents: ${totals.openCents}`);
// The next line fails under tsc --checkJS: cents must be a number
// invoices.push({ id: 'inv-4', cents: '500', paid: false });