-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.patterns.js
More file actions
48 lines (45 loc) · 1.22 KB
/
string.patterns.js
File metadata and controls
48 lines (45 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @title: find substring in sentence
* @description: Simple function find substring / patterns
* @author: Thorsten Kober
* @email: [email protected]
*/
function numPattern(word, pattern) {
const wordLength = word.length;
const patternLength = pattern.length;
let wordIndex = 0;
let patternIndex = 0;
let start = 0;
let count = 0;
while (wordIndex < wordLength) {
if (word[wordIndex] === pattern[patternIndex]) {
patternIndex++;
wordIndex++;
if (patternIndex === patternLength) {
// console.log(`found at: ${wordIndex - patternLength}`);
patternIndex = 0;
count++;
start++;
wordIndex = start;
// console.log(`next start: ${start}`);
}
} else {
start++;
wordIndex = start;
}
}
return count;
}
// npx jest algorithms/string/string.patterns.js
test('numPattern()', () => {
expect(numPattern('AAAAAAAAAAAAAAAAAB', 'AAAAB')).toEqual(1);
});
test('numPattern()', () => {
expect(numPattern('AAAAAAAABAAAAAAAAB', 'AAAAB')).toEqual(2);
});
test('numPattern()', () => {
expect(numPattern('lorie loled', 'lol')).toEqual(1);
});
test('numPattern()', () => {
expect(numPattern('AABAACAADAABAABA', 'AABA')).toEqual(3);
});