任务
把每个资源的月度成本累加到其 owner 上,按成本降序、同额按 owner 名称排序输出。
契约
- 输入:JSON 对象:{ resources: [{ name, owner, monthlyCost }] }
- 输出:JSON 对象数组:[{ owner, monthlyCost }],按成本降序、再按 owner 排序
样例
- 输入
{"resources":[{"name":"db","owner":"platform","monthlyCost":420.5},{"name":"cache","owner":"platform","monthlyCost":79.5},{"name":"cdn","owner":"web","monthlyCost":120}]}-> 期望[{"owner":"platform","monthlyCost":500},{"owner":"web","monthlyCost":120}]。platform 的两个资源合计 500,排在 web 之前。 - 输入
{"resources":[{"name":"cdn","owner":"web","monthlyCost":120},{"name":"batch","owner":"data","monthlyCost":120}]}-> 期望[{"owner":"data","monthlyCost":120},{"owner":"web","monthlyCost":120}]。总额相同时按 owner 名称排序,报告保持稳定。
参考实现
function solve({ resources }) {
const totals = new Map();
for (const resource of resources) {
totals.set(resource.owner, (totals.get(resource.owner) ?? 0) + resource.monthlyCost);
}
return [...totals.entries()]
.map(([owner, monthlyCost]) => ({ owner, monthlyCost: +monthlyCost.toFixed(2) }))
.sort((a, b) => b.monthlyCost - a.monthlyCost || a.owner.localeCompare(b.owner));
}
为什么有效
成本优化的第一步是归属。缺少标签或归属错误的开销,会让每一次优化讨论都变成轶事。
只在最后统一取整;逐个资源取整再求和会让账单出现偏差。