Skip to content

Commit 276c348

Browse files
committed
Implement find function to locate character index in string with detailed comments and explanations
1 parent e2c7e37 commit 276c348

File tree

1 file changed

+20
-12
lines changed
  • Sprint-3/4-stretch-investigate

1 file changed

+20
-12
lines changed

Sprint-3/4-stretch-investigate/find.js

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,33 @@
11
function find(str, char) {
2+
// Start searching from the first character (index 0)
23
let index = 0;
34

5+
// Continue looping while index is less than the length of the string
6+
// This prevents us from going beyond the last character of the string
47
while (index < str.length) {
8+
// Check if the current character matches the one we are looking for
59
if (str[index] === char) {
10+
// If found, return the current index position
611
return index;
712
}
8-
index++;
13+
// Move to the next character in the string
14+
index++; // This increments index by 1, so the loop moves through each character
915
}
16+
17+
// If we finish the loop without finding the character, return -1
18+
// This means the character does not exist in the string
1019
return -1;
1120
}
1221

13-
console.log(find("code your future", "u"));
14-
console.log(find("code your future", "z"));
15-
16-
// The while loop statement allows us to do iteration - the repetition of a certain number of tasks according to some condition
17-
// See the docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
22+
// Test examples:
23+
console.log(find("code your future", "u")); // Should output the first index of 'u'
24+
console.log(find("code your future", "z")); // Should output -1 since 'z' is not in the string
1825

19-
// Use the Python Visualiser to help you play computer with this example and observe how this code is executed
20-
// Pay particular attention to the following:
26+
/*
27+
Explanation:
28+
a) The 'index' variable starts at 0 and increments by 1 each loop (index++), allowing the function to check each character in the string.
29+
b) The 'if' statement checks whether the current character (str[index]) matches the character we're searching for.
30+
c) 'index++' is used to move forward to the next character in the string on each loop iteration.
31+
d) The condition 'index < str.length' ensures the loop only runs while 'index' is a valid position inside the string, preventing errors.
32+
*/
2133

22-
// a) How the index variable updates during the call to find
23-
// b) What is the if statement used to check
24-
// c) Why is index++ being used?
25-
// d) What is the condition index < str.length used for?

0 commit comments

Comments
 (0)