Creating permutations by changing case in JavaScript


Problem

We are required to write a JavaScript function that takes in a string of characters, str, as the first and the only argument.

Our function can transform every letter individually to be lowercase or uppercase to create another string. And we should return a list of all possible strings we could create.

For example, if the input to the function is

Input

const str = 'k1l2';

Output

const output = ["k1l2","k1L2","K1l2","K1L2"];

Example

Following is the code −

 Live Demo

const str = 'k1l2';
const changeCase = function (S = '') {
   const res = []
   const helper = (ind = 0, current = '') => {
      if (ind >= S.length) {
         res.push(current)
         return
      }
      if (/[a-zA-Z]/.test(S[ind])) {
         helper(ind + 1, current + S[ind].toLowerCase())
         helper(ind + 1, current + S[ind].toUpperCase())
      } else {
         helper(ind + 1, current + S[ind])
      }
   }
   helper()
   return res
};
console.log(changeCase(str));

Output

[ 'k1l2', 'k1L2', 'K1l2', 'K1L2' ]

Updated on: 24-Apr-2021

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements