Coding Challenge 2
The Problem
As always, there are several solutions to this problem I'm sure, but I will walk through mine at my current understanding of JavaScript.
Given a lowercase string, create a function which returns a list where each letter of the word has a chance to be the capitalized letter in the string. Ignore white spaces and skip to the next letter if the string has a space.
If input is 'hello', output would be [ 'Hello', 'hEllo', 'heLlo', 'helLo', 'hellO' ]
likewise, if input was "sun shines" output is [ 'So cool', 'sO cool', 'so Cool', 'so cOol', 'so coOl', 'so cooL' ]
Breaking down the problem
We need a function with a string parameter, we need a variable to store the list in, & we need to grab each letter of the word and capitalize it. Also, remembering the last blog I posted about the immutability of strings.
Code
First, I create my function and variable to hold my list.
function wave(str) {
let output = [];
}
Then we want to loop over the argument. We also know that we want to return this list so let's do that too.
function wave(str) {
let output = [];
for (let i = 0; i < str.length; i++) {
}
return output;
}
We also know that we need to check if the current index is a white space character and if it isn't white space then we want to do something, right?
function wave(str) {
let output = [];
for (let i = 0; i < str.length; i++) {
if (str[i] != " ") {
}
}
return output;
}
The Array push method will push a value into an array, so I chose to use this to store each iteration. Also, the String slice method will provide us a way to get a new string sliced at a set starting index and a stopping index. Meanwhile, the String charAt method allows you to grab a single character at a given index
I invite you to look at documentation of these methods to see how they work, if you don't know them, that is.
Solution
function wave(str) {
let output = [];
for (let i = 0; i < str.length; i++) {
if (str[i] != " ") {
output.push(str.slice(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1, str.length))
}
}
return output;
}
Issue
My main issue was not setting a stopping point on my second slice method so my last output was undefined.