Maclean Pinto
Maclean Pinto

Reputation: 1135

How to wait for a recurisvie function to complete in typescript

I have written a program to De-serialize a binary tree into a string.

let serializedTreeString: string = '';
class BinaryTreeNode {
    _val: number;
    _left: BinaryTreeNode;
    _right: BinaryTreeNode;
    constructor(val: number, left: BinaryTreeNode = null, right: BinaryTreeNode = null) {
        this._val = val;
        this._left = left;
        this._right = right;

    }
}

function _serialize(current: BinaryTreeNode) {
    if (current === null) {
        serializedTreeString = serializedTreeString.concat('-1,');
    } else {
        serializedTreeString = serializedTreeString.concat(current._val + ',');
        _serialize(current._left);
        _serialize(current._right);
    }
}

function serialize(current: BinaryTreeNode) {
    let serializedTreeString: string = '';
    _serialize(current);
    console.log(serializedTreeString);
}

let root: BinaryTreeNode = new BinaryTreeNode(20, new BinaryTreeNode(8, new BinaryTreeNode(4), new BinaryTreeNode(12, new BinaryTreeNode(10), new BinaryTreeNode(14))), new BinaryTreeNode(22));
serialize(root);

When i print the serializedTreeString its blank as java script is asynchronous. I could use a counter, which would increase on every call of _serialize and decrease inside _serialize. This way i can check if the counter has reached 0 and print the value of serializedTreeString. Is there a better way to do this?

Upvotes: 0

Views: 28

Answers (1)

Dmitriy
Dmitriy

Reputation: 2822

You are getting an empty string not because javascript is async (all calls in your example are sync). It is because you are shadowing outer variable definition inside serialize. Just remove let in front of serializedTreeString:

function serialize(current: BinaryTreeNode) {
    serializedTreeString = '';
    _serialize(current);
    console.log(serializedTreeString);
}

In general though it is best to avoid global variables in such cases and use return instead:

class BinaryTreeNode {
    _val: number;
    _left: BinaryTreeNode;
    _right: BinaryTreeNode;
    constructor(val: number, left: BinaryTreeNode = null, right: BinaryTreeNode = null) {
        this._val = val;
        this._left = left;
        this._right = right;

    }
}

function serialize(current: BinaryTreeNode): string {
    if (current === null) {
        return "-1,";
    } else {
        return `${current._val},${serialize(current._left)}${serialize(current._right)}`;
    }
}

let root: BinaryTreeNode = new BinaryTreeNode(20, new BinaryTreeNode(8, new BinaryTreeNode(4), new BinaryTreeNode(12, new BinaryTreeNode(10), new BinaryTreeNode(14))), new BinaryTreeNode(22));
console.log(serialize(root));

Upvotes: 1

Related Questions