Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript recursion within an exports function: not a function

perennial newbie question: how do i fix this "not a function" error:

exports.height = (input) => {
    function height(node, height) {
        if (node.left) {
            if (height > maxHeight) {
                maxHeight = height;
            }
            **height(node.left, height+1); // <-- Says "Not a function"**
        }
    }

    var maxHeight = 0;
    height( input, 0 ); // <--- This works fine.

    return maxHeight;
}

says, TypeError: height is not a function

  at height (BinarySearchTree.js:53:5)

Thanks! Nilesh

like image 855
Nilesh Avatar asked Jul 18 '26 00:07

Nilesh


1 Answers

You accidentally shadowed your height variable

function height(node, height) {
    if (node.left) {
        if (height > maxHeight) {
            maxHeight = height;
        }
        height(node.left, height+1);
    }
}

var maxHeight = 0;
height( input, 0 ); // 0 is obviously not a function ^_^

Try renaming the height parameter to something like h

function height(node, h) {
    if (node.left) {
        if (h > maxHeight) {
            maxHeight = h;
        }
        return height(node.left, h+1); // don't forget your return
    }
}

var maxHeight = 0;
height( input, 0 );

All that said, you might want to reconsider your function alltogether

function height (node) {
  if (node === undefined)
    return -1;
  else
    return Math.max(height(node.left), height(node.right)) + 1;
}
like image 147
Mulan Avatar answered Jul 20 '26 12:07

Mulan