Skip to content

Commit 99f011b

Browse files
committed
Review changes and added test case for overlapping substring
1 parent bf5c4a7 commit 99f011b

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

String/CountSubstrings.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,14 @@ const countSubstrings = (str, substring) => {
1313
throw new TypeError('Argument should be string')
1414
}
1515

16-
if (substring.length <= 0) return (str.length + 1)
16+
if (substring.length === 0) return str.length + 1
1717

1818
let count = 0
1919
let position = str.indexOf(substring)
2020

2121
while (position > -1) {
22-
++count
23-
position = str.indexOf(substring, ++position)
22+
count++
23+
position = str.indexOf(substring, position + 1)
2424
}
2525

2626
return count

String/test/CountSubstrings.test.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,11 @@ describe('CountSubstrings', () => {
4242
const count = countSubstrings(str, substring)
4343
expect(count).toBe(6)
4444
})
45+
46+
it('should return correct result when input is overlapping substring', () => {
47+
const str = 'aaa'
48+
const substring = 'aa'
49+
const count = countSubstrings(str, substring)
50+
expect(count).toBe(2)
51+
})
4552
})

0 commit comments

Comments
 (0)