JSFiddle - React, Tailwind, and code Playground

by samur3

JavaScript

let digits1 = ''
let digits2 = '2';
let digits3 = '23';
let digits4 = '22';
let digits5 = '234';
let digits6 = '999';



var letterCombinations = function(digits) {
		let len = digits.length;
    if(len === 0) return [];    
    let numbersToLetters = initNumbersToLetters();
    if(len === 1) return numbersToLetters[digits];
    
    let stackComb1 = new Array();
    let stackComb2 = new Array();
    
    stackComb1 = [...numbersToLetters[digits[0]]];
    digits = digits.slice(1);    
    digits.split('').forEach((digit) => {
    	let chars = [...numbersToLetters[digit]];      
      addOptions(chars,stackComb1,stackComb2);              
    });
    return result(stackComb1,stackComb2);
};

function result(stackComb1,stackComb2){
debugger;
	return stackComb1.length > 1 ? stackComb1 : stackComb2;
}

function addOptions(chars,stackComb1,stackComb2){
	let currentStack = null;
  let stackToFill = null;
	if(stackComb1.length > 1){
  	currentStack = stackComb1;
    stackToFill = stackComb2;
  }
  else{
  	currentStack = stackComb2;
    stackToFill = stackComb1;
  }
  while(currentStack.length > 0){
  	let option = currentStack.pop();
   debugger;
    for(let i=0; i < chars.length; i++){      	
    	let valueToPush = option + chars[i];
    	stackToFill.push(valueToPush);
    }
  }
}

function initNumbersToLetters(){
	return {
  	2 : ['a','b','c'],
    3 : ['d','e','f'],
    4 : ['g','h','i'],
    5 : ['j','k','l'],
    6 : ['m','n','o'],
    7 : ['p','q','r','s'],
    8 : ['u','v','w'],
    9 : ['w','x','y','z']
  }  
}

//console.log(letterCombinations(digits1));
//console.log(letterCombinations(digits2));
//console.log(letterCombinations(digits3));
//console.log(letterCombinations(digits4));
//console.log(letterCombinations(digits5));
console.log(letterCombinations(digits6));