I can't seem to figure it out how to make a wave from a string in Javascript.
Rules:
Expected result:
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
wave (" h e y ") => [" H e y ", " h E y ", " h e Y "]
wave ("") => []
This is as far as I got. Current code will give me an answer ["hello", "hello", "hello", "hello", "hello"]
. I'm thinking using second for loop and somehow capitalize each new letter but I'am stumped. Also I would appreciate if answer would avoid using loop inside loop O(n^2)
. Because of BIG O Scalability.
const wave = (str) => {
if(typeof str === 'string' && str === str.toLowerCase()){
for (let index = 0; index < str.length; index++) {
array.push(str);
}
for (let index = 0; index < str.length; index++) {
console.log(array);
}
}else{
alert(`${str} is either not a string or not lowercase`);
}
}
wave("hello");
You could take an outer loop for visiting the characters and if a non space character is found, create a new string with an uppercase letter at this position.
function wave(string) {
var result = [],
i;
for (i = 0; i < string.length; i++) {
if (string[i] === ' ') continue;
result.push(Array.from(string, (c, j) => i === j ? c.toUpperCase() : c).join(''));
}
return result;
}
console.log(wave("hello")); // ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
console.log(wave(" h e y ")); // [" H e y ", " h E y ", " h e Y "]
console.log(wave("")); // []
.as-console-wrapper { max-height: 100% !important; top: 0; }
This does it. However, if you have spaces in your string, it will output string without any "waved letter" (since also space is handled):
const wave = (str = '') => {
return str
.split('')
.map((letter, i, arr) => `${arr.slice(0, i)}${letter.toUpperCase()}${arr.slice(i + 1, arr.length)}`.replace(/,/g, ''));
}
console.log(wave('wave'));
console.log(wave('foo bar'));
console.log(wave());
You can take each char in string in for loop and make it uppercase and the append with prefix and post fix string
var array=[];
const wave = (str) => {
if(typeof str === 'string' && str === str.toLowerCase()){
for (let index = 0; index < str.length; index++) {
if (str[index] === ' ') continue;
waveChar=str.charAt(index).toUpperCase();
preStr=str.substring(0,index);
postStr=str.substring(index,str.length-1);
array.push(preStr+waveChar+postStr);
}
}else{
alert(`${str} is either not a string or not lowercase`);
}
}
wave("hello");
console.log(array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With