AlgoDaily Solution

1var assert = require('assert');
2
3function detectSubstring(str, subStr) {
4 let idxOfStart = 0,
5 j = 0;
6
7 for (i = 0; i < str.length; i++) {
8 // if match, compare next character of subStr with next of string
9 if (str[i] == subStr[j]) {
10 j++;
11 if (j == subStr.length) {
12 return i - (subStr.length - 1);
13 }
14 } else {
15 i -= j;
16 j = 0;
17 }
18 }
19
20 return -1;
21}
22
23// console.log(detectSubstring('ggraph', 'graph'));
24// console.log(detectSubstring('geography', 'graph'));
25// console.log(detectSubstring('digginn', 'inn'));
26
27try {
28 assert.equal(detectSubstring('thepigflewwow', 'flew'), 6);
29
30 console.log(
31 'PASSED: ' + "`detectSubstring('thepigflewwow', 'flew')` should return `6`"
32 );
33} catch (err) {
34 console.log(err);
35}
36
37try {
38 assert.equal(detectSubstring('twocanplay', 'two'), 0);
39
40 console.log(
41 'PASSED: ' + "`detectSubstring('twocanplay', 'two')` should return `0`"
42 );
43} catch (err) {
44 console.log(err);
45}
46
47try {
48 assert.equal(detectSubstring('wherearemyshorts', 'pork'), -1);
49
50 console.log(
51 'PASSED: ' +
52 "`detectSubstring('wherearemyshorts', 'pork')` should return `-1`"
53 );
54} catch (err) {
55 console.log(err);
56}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
44
var assert = require('assert');
console.log('Running and logging statements.');
function detectSubstring(str, subStr) {
// Fill in this method
return str;
}
console.log(detectSubstring('ggraph', 'graph'));
console.log(detectSubstring('geography', 'graph'));
console.log(detectSubstring('digginn', 'inn'));
try {
assert.equal(detectSubstring('thepigflewwow', 'flew'), 6);
console.log(
'PASSED: ' + "`detectSubstring('thepigflewwow', 'flew')` should return `6`"
);
} catch (err) {
console.log(err);
}
try {
assert.equal(detectSubstring('twocanplay', 'two'), 0);
console.log(
OUTPUT
Results will appear here.