1

This function finds into which the largest equilateral parts the field can be divided.

function field (width, height) {
  let big = Math.max(width, height);
  let small = Math.min(width, height);

  if (big / small === 1){
    let arr = [];
    arr.push(big);
    arr.push(small);
    return arr;
  }

  field(big-small, small);
}

field(1600, 500) // should be [100, 100]

It returns undefined, but if I use console.log before, it shows everything OK. Why?

Eugene P.
  • 1,517
  • 12
  • 16
  • if `big/small != 1` your function returns nothing (undefined). – James Apr 11 '19 at 19:11
  • Welcome to the stack overflow. You are getting undefined as you are not returning only when `big /small === 1` but in your case it won't happen. Just change this line `field(big-small, small);` with `return field(big-small, small);` and then the function will start work as it is suppose to be. – Sami Ahmed Siddiqui Apr 11 '19 at 19:25

1 Answers1

0

You need a return statement for the recursive call.

return field(big - small, small);

function field(width, height) {
    let big = Math.max(width, height);
    let small = Math.min(width, height);

    if (big === small) { // easier check
        let arr = [];
        arr.push(big);
        arr.push(small);
        return arr;
    }
    return field(big - small, small);
}

console.log(field(1600, 500));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392