Performing shifts within a string in JavaScript


Suppose we have a string str containing lowercase English letters, and an array of arrays arr, where arr[i] = [direction, amount] −

  • direction can be 0 (for left shift) or 1 (for right shift).

  • amount is the amount by which string s is to be shifted.

  • A left shift by 1 means remove the first character of s and append it to the end.

  • Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.

We are required to write a JavaScript function that takes in the string as the first argument and the array containing shift data as the second argument.

The function should iterate over the array and perform necessary shifts in the string and finally return the new string.

For example −

If the input string and the array are −

const str = 'abc';
const arr = [[0, 1], [1, 2]];

Then the output should be −

const output = 'cab';

because,

[0,1] means shift to left by 1. “abc” -> “bca”

[1,2] means shift to right by 2. “bca” -> “cab”

Example

The code for this will be −

 Live Demo

const str = 'abc';
const arr = [[0, 1], [1, 2]];
const performShifts = (str = '', arr = []) => {
   if(str.length < 2){
      return str;
   };
   let right = 0
   let left = 0;
   for(let sub of arr){
      if(sub[0] == 0){
         left += sub[1];
      }else{
         right += sub[1];
      };
   };
   if(right === left){
      return str;
   }
   if(right > left){
      right = right - left;
      right = right % str.length;
      return str.substring(str.length - right) + str.substring(0,
      str.length - right);
   }else{
      left = left - right;
      left = left % str.length;
      return str.substring(left) + str.substring(0,left);
   };
};
console.log(performShifts(str, arr));

Output

And the output in the console will be −

cab

Updated on: 27-Feb-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements