11// Implement a function repeatStr
2- const repeatStr = require ( "./repeat-str" ) ;
2+
33// Given a target string `str` and a positive integer `count`,
44// When the repeatStr function is called with these inputs,
55// Then it should:
@@ -9,24 +9,47 @@ const repeatStr = require("./repeat-str");
99// When the repeatStr function is called with these inputs,
1010// Then it should return a string that contains the original `str` repeated `count` times.
1111
12+ function repeatStr ( str , count ) {
13+ if ( count < 0 ) {
14+ throw new Error ( "Count must be a non-negative integer" ) ;
15+ } else if ( count === 0 ) {
16+ return "" ;
17+ } else {
18+ return str . repeat ( count ) ;
19+ }
20+ }
21+
1222test ( "should repeat the string count times" , ( ) => {
1323 const str = "hello" ;
1424 const count = 3 ;
1525 const repeatedStr = repeatStr ( str , count ) ;
1626 expect ( repeatedStr ) . toEqual ( "hellohellohello" ) ;
1727} ) ;
1828
19- // Case: handle count of 1:
20- // Given a target string `str` and a `count` equal to 1,
21- // When the repeatStr function is called with these inputs,
22- // Then it should return the original `str` without repetition.
29+ test ( "should return the original string when count is 1" , ( ) => {
30+ const str = "hello" ;
31+ const count = 1 ;
32+ const repeatedStr = repeatStr ( str , count ) ;
33+ expect ( repeatedStr ) . toEqual ( "hello" ) ;
34+ } ) ;
35+
2336
2437// Case: Handle count of 0:
2538// Given a target string `str` and a `count` equal to 0,
2639// When the repeatStr function is called with these inputs,
2740// Then it should return an empty string.
41+ test ( "should return an empty string when count is 0" , ( ) => {
42+ const str = "hello" ;
43+ const count = 0 ;
44+ const repeatedStr = repeatStr ( str , count ) ;
45+ expect ( repeatedStr ) . toEqual ( "" ) ;
46+ } ) ;
2847
2948// Case: Handle negative count:
3049// Given a target string `str` and a negative integer `count`,
3150// When the repeatStr function is called with these inputs,
3251// Then it should throw an error, as negative counts are not valid.
52+ test ( "should throw an error for a negative count" , ( ) => {
53+ expect ( ( ) => repeatStr ( "hello" , - 1 ) ) . toThrow ( ) ;
54+
55+ } ) ;
0 commit comments