Skip to content

Commit 95ba4bf

Browse files
committed
Refactor repeat function to return early for invalid input and remove redundant code
1 parent 2957d4b commit 95ba4bf

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

Sprint-3/2-practice-tdd/repeat.js

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,29 @@
11
function repeat(valueToRepeat, numOfTimes) {
2+
// Validate count
3+
if (!Number.isInteger(numOfTimes)) {
4+
return "Invalid count: count should be an integer";
5+
}
6+
if (numOfTimes < 0) {
7+
return "Negative number invalid";
8+
}
9+
if (numOfTimes === 0) {
10+
return "";
11+
}
12+
13+
// Convert arrays to empty string
14+
if (Array.isArray(valueToRepeat)) {
15+
valueToRepeat = "";
16+
}
17+
18+
// Convert other types to string
19+
const strValue = String(valueToRepeat);
20+
21+
// Repeat the string
222
let repeatedValue = "";
3-
if (numOfTimes > 0 && Number.isInteger(numOfTimes)) {
4-
for (let i = 0; i < numOfTimes; i++) {
5-
repeatedValue += valueToRepeat;
6-
}
7-
} else if (numOfTimes === 0) {
8-
repeatedValue = "";
9-
} else if(numOfTimes < 0) {
10-
repeatedValue = "Negative number invalid";
11-
} else if(!Number.isInteger(numOfTimes)) {
12-
repeatedValue = "Invalid count: count should be an integer"
23+
for (let i = 0; i < numOfTimes; i++) {
24+
repeatedValue += strValue;
1325
}
26+
1427
return repeatedValue;
1528
}
1629

0 commit comments

Comments
 (0)