-
-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathcount.js
More file actions
40 lines (32 loc) · 750 Bytes
/
count.js
File metadata and controls
40 lines (32 loc) · 750 Bytes
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
/**
* Original file:
*
function countChar(stringOfCharacters, findCharacter) {
return 5
}
module.exports = countChar;
*
* End of file
*/
// Implementation:
/**
* Counts the number of times a character occurs in a string
* @param {string} str - The string to search
* @param {string} char - The single character to search for
* @returns {number} - The count of occurrences
*/
function countChar(str, char) {
// Input validation
if (typeof str !== 'string' || typeof char !== 'string' || char.length !== 1) {
return 0;
}
let count = 0;
// Loop through each character in the string
for (let i = 0; i < str.length; i++) {
if (str[i] === char) {
count++;
}
}
return count;
}
module.exports = countChar;