|
| 1 | + |
| 2 | +## Description |
| 3 | + |
| 4 | +Complete the solution so that it returns the number of times the search_text is found within the full_text. |
| 5 | + |
| 6 | +```js |
| 7 | +searchSubstr( fullText, searchText, allowOverlap = true ) |
| 8 | +``` |
| 9 | + |
| 10 | +so that overlapping solutions are (not) counted. If the searchText is empty, it should return 0. |
| 11 | + |
| 12 | +### Examples |
| 13 | +```js |
| 14 | +searchSubstr('aa_bb_cc_dd_bb_e', 'bb') # should return 2 since bb shows up twice |
| 15 | +searchSubstr('aaabbbcccc', 'bbb') # should return 1 |
| 16 | +searchSubstr( 'aaa', 'aa' ) # should return 2 |
| 17 | +searchSubstr( 'aaa', '' ) # should return 0 |
| 18 | +searchSubstr( 'aaa', 'aa', false ) # should return 1 |
| 19 | +``` |
| 20 | + |
| 21 | +**Kata's link**: [Return substring instance count](https://www.codewars.com/kata/return-substring-instance-count-2) |
| 22 | + |
| 23 | +## Best Practices |
| 24 | + |
| 25 | +**First:** |
| 26 | +```js |
| 27 | +function searchSubstr(fullText, searchText, allowOverlap) { |
| 28 | + if(searchText == '') return 0; |
| 29 | + var re = new RegExp(searchText, 'g'); |
| 30 | + if(allowOverlap) { |
| 31 | + var count = 0; |
| 32 | + while(re.exec(fullText)) {count++; re.lastIndex -= searchText.length - 1;} |
| 33 | + return count; |
| 34 | + } else return (fullText.match(re) || []).length || 0; |
| 35 | +} |
| 36 | +``` |
| 37 | + |
| 38 | +**Second:** |
| 39 | +```js |
| 40 | +function searchSubstr( fullText, searchText, allowOverlap ){ |
| 41 | + if(fullText == "" || searchText == "") return 0; |
| 42 | + |
| 43 | + var re = new RegExp(searchText, "g"), count = 0, match; |
| 44 | + while (match = re.exec(fullText)) { |
| 45 | + count++; |
| 46 | + if(allowOverlap) re.lastIndex = match.index+1; |
| 47 | + } |
| 48 | + return count; |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +## My solutions |
| 53 | +```js |
| 54 | +function countOverlap (reg, matched, fullText, searchText) { |
| 55 | + let count = matched.length; |
| 56 | + for (let i = 0, l = matched.length; i < l; i++) { |
| 57 | + const start = fullText.indexOf(matched[0]) + 1; |
| 58 | + const end = start + searchText.length; |
| 59 | + const sub = fullText.slice(start, end + 1); |
| 60 | + |
| 61 | + if (reg.test(sub)) { |
| 62 | + count += 1; |
| 63 | + } |
| 64 | + |
| 65 | + fullText = fullText.slice(start + searchText.length); |
| 66 | + } |
| 67 | + return count; |
| 68 | +} |
| 69 | + |
| 70 | +function searchSubstr( fullText, searchText, allowOverlap = true ){ |
| 71 | + if (!searchText) { |
| 72 | + return 0; |
| 73 | + } |
| 74 | + |
| 75 | + const reg = new RegExp(searchText, 'g'); |
| 76 | + const matched = fullText.match(reg); |
| 77 | + |
| 78 | + return allowOverlap ? (matched ? countOverlap(reg, matched, fullText, searchText) : 0) : (matched ? matched.length : 0); |
| 79 | +} |
| 80 | +``` |
0 commit comments