0

Does anybody see below javascript recursive with shift() return? Even three times shift() array still run 'while loop'

function combine(nums) {
    while (nums.length) {
        let r = nums.shift();
        console.log(r, ':',  nums);
        combine(nums.slice(0));
  }
}

combine([1,2,3])
---------------  return -----------
    1 : [ 2, 3 ]
    2 : [ 3 ]
    3 : []
    3 : []
    2 : [ 3 ]
    3 : []
    3 : []
------------------------------------
3
  • That's correct as marked duplicate by Andy. I forget to add return combine(nums.slice(0)); Thank you Andy Commented Nov 19, 2019 at 12:00
  • 1
    A return will avoid while to continue the next iteration. Commented Nov 19, 2019 at 12:37
  • I agree Akshay's reply Commented Nov 19, 2019 at 21:11

3 Answers 3

1

Your example works as expected. I altered it slightly to maybe show you more clearly why it behaves this way:

Also, what's your question?

function combine(nums, depth) {
  console.log(`Starting depth ${depth} with [${nums}]`);
    while (nums.length) {
      let r = nums.shift();
      let newArr = nums.slice(0);
      console.log(`Removed "${r}". Firing with [${newArr}]`);
      combine(nums.slice(0), depth+1);
      console.log(`Returned to depth ${depth}`);
  }
  console.log(`While end at depth ${depth}`);
}

combine([1,2,3], 0) 
Sign up to request clarification or add additional context in comments.

1 Comment

I am very impressed by kaczmen's answer.
0

The slice() method returns a shallow copy of a portion of an array into a new array object

By calling combine(nums.slice(0)) you are not performing next function call on same the nums array, cause slice will return new array.

Use:

function combine(nums) {
    while (nums.length) {
        let r = nums.shift();
        console.log(r, ':',  nums);
        combine(nums);
  }
}

combine([1,2,3]);

Comments

0

I guess you shouldn't "combine" recursion and while loop. Even more, I believe recursion is a bad practice.

function combine(nums) {
    while (nums.length) {
        let r = nums.shift();
        console.log(r, ':',  nums);
        //combine(nums.slice(0)); <- this line is a problem
  }
}

combine([1,2,3])
---------------  return -----------
    1 : [ 2, 3 ]
    2 : [ 3 ]
    3 : []
------------------------------------

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.