Swapping string case using a binary number in JavaScript


Problem

We are required to write a JavaScript function that takes in a string str and a number n. Our function should change the given string str using n.

Each bit in n will specify whether or not to swap the case for each alphabetic character in s −

If the bit is 1, swap the case; if its 0, leave it as is. When we are finished with the last bit of n, start again with the first bit.

And finally, we should return the new string thus formed.

Example

Following is the code −

 Live Demo

const str = 'hey there';
const num = 21;
const swapCase = (str = '', num = 1) => {
   const alphaLength = str
   .split('')
   .reduce((acc, val) => val.toLowerCase() !== val.toUpperCase() ? ++acc : acc, 0);
   let binary = num.toString(2);
   while(binary.length < alphaLength){
      binary += binary;
   };
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(el.toUpperCase() !== el.toLowerCase() && +binary[i] === 1){
         if(el.toLowerCase() === el){
            res += el.toUpperCase();
         }else{
            res += el.toLowerCase();
         }
      }else{
         res += el;
      };
   };
   return res;
};
console.log(swapCase(str, num));

Output

Following is the console output −

HeY TheRe

Updated on: 17-Apr-2021

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements