This code is supposed to count each character in a given string and account for error handling and type casting as well, and it should do it in the most efficient manner possible, with O(n) being an upper limit for both time and memory. I have gone through my process for problem solving which involves explaining the problem in my own words, looking at the inputs, the outputs, if the answer is even possible given the I/O, and then refactoring my code. Please, if anyone sees a better way to accomplish this then let me know.
function characterCounter(str) {
// Error Handling
// No input
if (!str) {
return "String input required";
}
// attempt to type cast non strings
if (typeof str !== "string") {
str = str.toString();
// input could not be successfully type casted
if (typeof str !== "string") {
return "Invalid input";
}
}
const stringLen = str.length;
const result = {};
let i = 0;
// loop through each character for O(n) time complexity and O(n) space complexity
// since the object grows based on input size
for (; i < stringLen; i++) {
// If string not in object as a key then add it and set value to 1
if (result[str[i]] === undefined && str[i] !== " ") {
result[str[i].toLowerCase()] = 1;
} else {
if (str[i] !== " ") {
// add one to value at current key
result[str[i]]++;
}
}
}
return result;
}
// Returns an object which allows O(1) for insert, deletion, access, and O(n) for searching...
console.log(characterCounter("Hello, World!"));