Add spaces to a particular index within a string

I'm currently tackling a challenging problem on Codewars.

Objective

Your goal in this Kata is to develop a function that transforms a string into a Mexican Wave. The output should be an array where each uppercase letter represents a person standing up.

Guidelines

  1. The input string will always be in lowercase, but it may be empty.
  2. If the character in the string is whitespace, treat it as an empty seat. Example wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

Click here to view my current code on repl.it

This is my thought process:

  1. Convert argument into an array
  2. Modify each index of the array accordingly to create a wave pattern
  3. Transform the array back into a string
  4. Add spaces before logging to the console and then repeat the loop

I am struggling with figuring out how to use

for(var j = 0; j < indexSpaceNumber.length; j++){
      //join and add in the spaces at their former index before returning string
      strToArray[indexSpaceNumber[j]].slice(0, " ");
      }

To correctly insert spaces into the string.

Any guidance or tips would be greatly appreciated. I feel like I am so close, yet also frustratingly far from solving this.

Answer №1

The concept revolves around the following steps:

  1. Iterate through each character
  2. Replace the original character in the string with an uppercase equivalent

To achieve this, you can utilize Array.from() to convert the string into an array, and then map each element to a new string. If a character is a space, return something falsy (an empty string as per the example). Once the array is created, filter out all falsy values:

const wave = str =>
  Array.from(str, (c,i) => // convert the string to an array
    // replace the original character with its uppercase version 
    c === ' ' ?
    ''
    :
    `${str.substring(0, i)}${c.toUpperCase()}${str.substring(i + 1)}`
  ).filter(c => c)

const result = wave("hello") 

console.log(result)

Answer №2

To transform strings with spaces

function capitalizeWithWave(str) {
  let result = []
  str.toLowerCase().split('').forEach((value, index) => {
    if(value == ' ') return;
    result.push( str.substr(0, index) + value.toUpperCase() + str.substr(index + 1) )
  });
  return result
}

console.log(capitalizeWithWave("hello hello"))

Answer №3

I'd choose recursion ;)

Consider that a string of length n requires an array of the same length as your exit condition.

You can determine the pattern for the next string based on the length of the array in each iteration:

hello []            [Hello]              0: uppercase 1st char and append
hello [Hello]       [Hello hEllo]        1: uppercase 2nd char and append
hello [Hello hEllo] [Hello hEllo heLlo]  2: uppercase 3rd char and append
...

const wave =
  (str, arr = []) =>
    str.length === arr.length
      ? arr
      : wave
          ( str
          , [ ...arr
            ,   str.slice(0, arr.length)
              + str[arr.length].toUpperCase()
              + str.slice(arr.length + 1)
            ]
          );

console.log(wave('hello'));

Answer №4

Iterate through each character in a string and create a new string by:

const wave = str => {
  const res = [];
  for (let i = 0; i < str.length; i++) {
    res.push(`${str.slice(0, i)}${str[i].toUpperCase()}${str.slice(i + 1)}}`);
  }
  return res;
};

console.log(wave("hi my name is rylan"));

// Another approach using Array.splice
const wave2 = str => {
  const res = [];
  for (let i in str) {
    const temp = Array.from(str);
    temp.splice(i, 1, temp[i].toUpperCase());
    res.push(temp)
  } 
  return res.map(x => x.join(''));
};

console.log(wave2("hi my name is rylan"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing an element in an array within a SMARTY template

Within the Smarty framework, I have a variable that stores an array named $COMMENTS. To access this information, I used $COMMENTS|@print_r and below is the output: Array ( [0] => ModComments_CommentsModel Object ( [data:private] => Arr ...

I'm having an issue where whenever I click on a different page, I keep getting redirected back to the first page

Upon conducting research, I discovered that by implementing the refined code below, I was able to resolve my issue (my other html was also corrected using this solution) setTimeout(function() { datatable_FTP.ajax.reload(null, false); }, 30000); Although I ...

Tips for effectively sorting through multiple sets of data within a controller

This is my current approach and it is functioning correctly $scope.data = $filter('filter')($scope.data, {dataType: term ,status : 'F'}); However, I need to filter the data based on two status values $scope.data = $filter('filt ...

Send a redirect after a certain delay to a URL stored in a variable outside of the current scope

Upon making an ajax request, the JSON response contains a link that needs to redirect the user to another page after 3 seconds. The current approach used is: response = JSON.parse(res); var link = response.link; setTimeout("window.location.href=link",300 ...

Getting an Object in PostgreSQL without the need for square brackets wrapping when using Node.js and Express

I'm currently utilizing PostgreSQL alongside node-postgres: pool, Node.js, and express to execute some basic queries. The issue I encounter is that the returned object is wrapped within square brackets, but my preference is to receive it without them. ...

Accessing a variable across multiple windows in Chrome DevTools

How can I access a variable across multiple windows? I am looking to utilize the Chrome Devtools console from various domains. Thank you in advance! https://i.sstatic.net/GJjE4.png ...

Is the Handlebars if statement not performing as expected?

I am facing an issue with creating a condition within my view. I have used the same method before to set up conditions and it worked fine, but for some reason it is not working here. My goal is to hide certain content from the user if a specific conditio ...

Implement a "please wait" JavaScript modal on the ASPX DetailView insert button

Trying to utilize the insert functionality of an aspx DetailsView, I am looking to display a javascript modal popup window while a new record is being processed and added to the database. Despite my efforts to trigger the popup using DetailsView_ItemComman ...

Storing extensive JSON data with AJAX, jQuery, and Java

Currently, I am utilizing jQuery AJAX to call a server-side method and sending a JSON string to the controller. Everything works smoothly when the JSON size is small, but as soon as it exceeds 7kb, the server side rejects the JSON string. I suspect that t ...

Unravel the mysterious array contents

I am looking to translate array values for use in json data. The goal is to place the values in contentvalue based on the content type into json. Currently, it is displaying null. I aim to reposition the array value as $zip_num=$content->zip; based on c ...

Exploring the efficiency of including arrays in PHP

How will the performance of "header.php" be impacted if I include a large PHP array? For instance, if I have a 1GB PHP array in a file called "data.php" that looks like $data = array( //1GB of data ) What type of performance hit can I expect when I inclu ...

Tips for executing a callback function when triggering a "click" event in jQuery?

Having trouble triggering a custom event in the callback of a trigger call. Attempted solutions: var $input = $( ".ui-popup-container" ).find( "input" ).eq(2); function runtests () { console.log("clicked the input"); }; $input.trigger('click&ap ...

What is the process for adjusting the font size of a custom rendering on an off-screen canvas using three.js?

When it comes to using custom fonts and rendering them on an off-screen canvas, there is a common issue I've encountered. Even though I have managed to make it work, adjusting the size of the font rendering seems to be causing some trouble - resulting ...

Can you explain the difference between CDN and ESM builds in vue.js?

According to the Vue.js documentation, there are differences in syntax depending on whether you are using the CDN or ESM build of Vue.js. What is the significance of having two different builds and how does it result in a difference in usage syntax? Infor ...

"Exploring the power of Vue3's composition API in managing the

Trying to implement an accordion component in Vue 3, but encountering a strange comparison issue. I'm attempting to execute a function within the accordionitem - specifically the toggle operation. However, despite numerous attempts, I am unable to mo ...

Tips for creating Firestore rules for a one-on-one messaging application

After creating a one to one chat app for a website using Firebase and Firestore, I am now looking to set up the Firebase Firestore rules for the same. The functionality of the app involves checking if the user is [email protected], then retrieving chatids ...

What is the rationale behind TypeScript's decision to permit omission of "this" in a method?

The TypeScript code below compiles without errors: class Something { name: string; constructor() { name = "test"; } } Although this code compiles successfully, it mistakenly assumes that the `name` variable exists. However, when co ...

Tips for structuring classes in an Angular project

What is the best approach for handling API responses using classes in various programming languages like TypeScript, JavaScript, Java, or others? Consider an application that requires three resources: Account (API: /account/:id) Car (API: /account/:id/c ...

What is causing React Js to fail loading css when switching from anchor tag to link tag?

I am learning React and experimenting with creating a basic static website using HTML templates in version ^18.2.0 of React JS. Everything seems to be functioning correctly, however, I have encountered an issue with page refresh. Specifically, when I repla ...

Enhance your search experience with Vue.js by highlighting important keywords across multiple search

I'm working on implementing a search feature that will bold the matching parts. For example, if I have the name 'John' and search for 'Jo Joh' in the same string, I want it to bold the part of 'John' that has the most mat ...