【发布时间】:2021-11-23 10:32:12
【问题描述】:
考虑以下对象:
// Example 1
{
gradeA: 100,
gradeB: 'No-Data',
gradeC: 'No-Data'
}
// Example 2
{
gradeA: 50,
gradeB: 40,
gradeC: 'No-Data'
}
// Example 3
{
gradeA: 75,
gradeB: 'No-Data',
gradeC: 'No-Data'
}
它们代表一个百分比,即所有三个等级的总和正好是 100。我们如何在可以计算它们的值时插入带有 'No-Data' 的键?
预期结果:
// Example 1
{
gradeA: 100,
gradeB: 0,
gradeC: 0
}
// Example 2
{
gradeA: 50,
gradeB: 40,
gradeC: 10
}
// Example 3
{
gradeA: 75,
gradeB: 'No-Data',
gradeC: 'No-Data'
}
// Note: This one can't be figured out so we leave it as is.
我的伪代码解决方案:
function interpolate(obj) {
// If only one key is a number:
// The value is 100:
// Set the other two keys to 0 and return the obj.
// The value is less than 100:
// return obj unchanged.
// If only one key is not a number:
// set that key to the sum of the two numbers minus 100 and return the obj.
}
这里有两个主要问题:
- 如何知道
'No-Data'.有多少和哪些键 - 我可以重新安排控制流以提高效率吗?
实际上,这些对象位于一个数组中,但我确信我可以自己解决这些问题。
【问题讨论】:
-
我猜你的意思是 40 在第二个示例的
gradeB字段中 -
@GuerricP 是的。我已经更正了。
-
除此之外,您的算法很好并且可以正常工作,所以我认为您应该发布实际代码,并且可能在codereview.stackexchange.com 上进行更合适的操作。除非您对此有更具体的问题。
标签: javascript node.js algorithm