DEV Community

Monu Kumar
Monu Kumar

Posted on

Function to Efficiently Reverse Alternate K-length Chunks of a String In Javascript

In this article, we will be discussing a code snippet that demonstrates how to reverse alternate chunks of a string. The code defines a function called strRevChunk(str, k) that takes in two parameters: a string str and an integer k.

Image description

A “chunk” is defined as a substring of the original string, with a length of “k” characters. The loop starts at the first character of the string (index 0) and increments by “k” characters each time, so it will grab chunks of the string in the following order: 0-k, k-2k, 2k-3k, etc.

If the current index (i) of the loop is divisible by 2*k, the function takes the current chunk and reverses it using the .split(), .reverse(), and .join() methods. Otherwise, it simply assigns the current chunk to a variable “chunk1” without reversing it.

The reversed or non-reversed chunk is then added to the “chunkStr” variable, which is initially an empty string. Once the loop completes, the “chunkStr” variable will contain the modified version of the original string, with chunks reversed every other iteration. The function then returns the modified “chunkStr” variable.

`function strRevChunk(str, k) {
let strLen = str.length
let chunk1, chunk2
let chunkStr = ""
for (let i = 0; i < strLen; i += k) {
if (i % (2*k) == 0) {
chunk1 = str.substr(i, k).split('').reverse().join('')
} else {
chunk1 = str.substr(i, k)
}
chunkStr += chunk1
}
return chunkStr
}

let str1 = 'abcdefghijkl'
console.log(strRevChunk(str1, 2))`

The code block also contains an example of how the function is used, where str1 = ‘abcdefghijkl’ and k = 2. Here we can see the function is called with str1 and 2 as its arguments, and the function will return the modified string “badcefghijkl”

let str1 = 'abcdefghijkl'
console.log(strRevChunk(str1, 2))
Output - badcefghijkl

Top comments (0)