Splitting an integer into its digits three ways

I’m trying to create a function that produces a 2D array of all possible three way splits of an integer.

e.g .

threeWay(1234)  // would return [[1, 2, 34], [1, 23, 4], [12,  3, 4]]
threeWay(12345) // would return [[1, 2, 345], [1, 23, 45], [1, 234, 5], [12, 34, 5], [12, 3, 45], [123, 4, 5]]

My code so far


function threeWaySplit(n){
	var s = n.toString(), potentials = [];
  
   	for(let i = 1; i < s.length-1; i++){
      var arr = []

    	for(let j = i; s.length; j++){
       		
          var first  = parseInt(s.slice(0, i));
          var second = parseInt(s.slice(i,j));
          var last   = parseInt(s.slice(j));
        	arr.push(first, second, last)
     
        }
      
    potentials.push(arr);
      
    }
  
  return potentials
}

Now I’m certain I’ve made errors in lsyntax as well as logic, when I try to run threeWaySplit(1234) in the chrome DevTools console, it seems to crash?

for(let j = i; s.length;

The end condition, s.length, will only result in the necessary falsey value when it’s 0, and as that will never happen it’s an infinite loop

1 Like