我正在准备一次面试,做黑客等级的准备问题,我想在这方面做得更好。这能得到一些反馈吗?如何改进我的代码?你是怎么解决这个问题的?
function getCount(array){
let counts = {}
for(let word of array){
let count = counts[word]
counts[word] = count ? counts[word] + 1: 1;
}
return counts
}
// Complete the checkMagazine function below.
function compareNoteMag(note,mag){
let noteKeys = Object.keys(note)
let string = 'Yes'
for(let key of noteKeys){
if(!mag[key]) string = 'No'
if(mag[key] < note[key]){
string = 'No'
}
}
console.log(string)
}
function checkMagazine(magazine, note) {
let magazineCount = getCount(magazine);
let noteCount = getCount(note);
compareNoteMag(noteCount,magazineCount)
};发布于 2018-07-22 15:48:26
在发布的代码中有几个性能问题:
noteKeys上的循环即使在它知道一个单词丢失之后也会继续。应该停下来。最好是一个函数做一件事。compareNoteMag做两件事:计算杂志中是否有足够的单词,并打印“是”或“否”。这应该是一个返回boolean的函数,它有一个适当的描述性名称。
第二个if在这里应该是一个else if:
if(!mag钥匙) string = 'No‘if(mag钥匙 < note钥匙){ string = 'No’}
这不仅效率低下(有时对第二个if进行不必要的评估),第二个if中的表达式有时是undefined和一个数字之间的比较,这可能会使人感到困惑并导致错误。
其中一些名字可能更好:
getCount返回计数图(复数),因此我将重命名为getCounts (复数)。getCount使用了一系列单词:words将是一个自然而直观的名称,而不是array。compareNoteMag计算打印的答案:answer将是一个自然而直观的名称,而不是string。而不是这样:
让计数=计数单词计数单词=计数?计数单词+ 1: 1;
JavaScript中的一种常用技术:
counts[word] = (counts[word] || 0) + 1;这很小,但我注意到有些草率:
function checkMagazine(...) { ... };末尾,分号是不必要的// Complete the checkMagazine function below.不应该在那里for(...){和if(...){中的圆括号周围放置空格。https://codereview.stackexchange.com/questions/199989
复制相似问题