I have a simple program:
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();
I was asked, in steps, to improve the above function:
- Decrease the time of execution, and
- Write unit-test(s) for it
This lead me to change the function to make it suitable for writing unit test(s).
Following is an attempt in that direction:
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);
My question
How can the original program be written differently:
- so that it is faster in execution,
- and such that it is unit-testable;
Do you have any comments on my attempt?