【发布时间】:2020-12-03 23:13:41
【问题描述】:
我有一个简单的程序:
function counterPattern() {
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("c");
} else if (i % 3 === 0) {
console.log("a");
} else if (i % 5 === 0) {
console.log("b");
}
}
}
counterPattern();
有人要求我逐步改进上述功能:
- 减少执行时间,并且
- 为其编写单元测试
这导致我更改函数以使其适合编写单元测试。
以下是朝那个方向的尝试:
function counterPattern(){
const pattern = []; // for making it unit-testable; returning pattern will help with snapshotting/matching without losing the order;
for ( let i=1; i<=100 ; i++ ) {
const rem3 = i % 3; // separate calculation to + the speed; same for next-line;
const rem5 = i % 5;
if ( rem3 === 0 && rem5 === 0 ) {
pattern.push('c');
}else if ( rem3 === 0 ){
pattern.push('a');
}else if ( rem5 === 0){
pattern.push('b');
}
}
// returning array would allow the caller to format the pattern
return pattern;
}
let result = counterPattern();
console.log(result);
我的问题
原程序怎么写不一样:
- 使其执行速度更快,
- 并且可以进行单元测试;
你们有我的尝试吗?
【问题讨论】:
-
我不认为快照对于直接测试这个功能是必要的。因为据我所知,它看起来像是一个纯函数,所以输出总是相同的。不过,我倾向于遵循 KentCDodds 测试范例,所以这当然是你的特权。
-
关于更快的执行:en.wikipedia.org/wiki/Fizz_buzz - 这是一个非常众所周知的问题,在互联网上的某个地方,您可能想到的每种语言的每种解决方案都可能存在。
-
@Jacob - 感谢您的意见;我想到了一个用例的快照测试,以便将来更改功能-但规格是相同的;或者相反,如果我们有一个结果开始并且功能体正在发展;另外,将检查 KentCDodds - 这对我来说是新的。
标签: javascript performance unit-testing execution-time