RKS_Code
RKS_Code

Reputation: 530

Is self recursion possible in arrow function?

   private recursiveFunction(node: any): boolean {
    var returnVal: boolean = false;
    if (node.name('ABC') !== -1) {
        return true;
    }
    if (node.children) {
        for (let child of node.children) {
            if (this.recursiveFunction(child)) {
                returnVal = true;
            }
        }
        return returnVal;
    }
}

Can I write this function as arrow function? Not sure if this is at all supported in javascript/typescript.

Edit I want to pass this function as arrow function in filter method of Array. For example

    let resultArray = someArray.filter((item: any) => {
        return item.hasValue();
    });

Upvotes: 0

Views: 317

Answers (2)

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

If I understand what you meant then how about:

let fn = (node: any) => {
    if (node.name('ABC') !== -1) {
        return true;
    }

    if (node.children) {
        return node.children.some(kid => fn(kid));
    }

    return node.hasValue();
};

let resultArray = someArray.filter(fn);

(code in playground)

Upvotes: 1

Matthias247
Matthias247

Reputation: 10396

Yes you can

var recursiveFunction = (node: any): boolean => {
    var returnVal: boolean = false;
    if (node.name('ABC') !== -1) {
        return true;
    }
    if (node.children) {
        for (let child of node.children) {
            if (recursiveFunction(child)) {
                returnVal = true;
            }
        }
        return returnVal;
    }
}

Upvotes: 1

Related Questions