JSFiddle - React, Tailwind, and code Playground

by Kumar Sidharth

JavaScript

const s = "abcd";

function getCombinations(s, baseChar = '') {
	const chars = [...s];
  
	// base cases 
  if (chars.length === 1) {
  	return [baseChar + s];
  }
  if (chars.length === 2) {
  	return [
    	baseChar + chars[0]+chars[1],
      baseChar + chars[1]+chars[0],
    ]
  }
  
  //
  let combinations = [];
  chars.forEach((c, index) => {
       const charCopy = [...chars];
       charCopy.splice(index, 1);
  		combinations.push(...getCombinations(charCopy, c));
    });
  return combinations;
}