1

When trying to return the amount of children containing :host found in an object, the function always returns undefined.

const plugin = stylelint.createPlugin(ruleName, isEnabled => {
  let childrenFound = 0;
  childrenFound = lookForChildren(rule.nodes, childrenFound);
  console.log(childrenFound); // Wrong Value: Always undefined
}


let lookForChildren = function(nodes, childFound) {

  if(childFound > 1) {

    console.log(childFound);

    return childFound;

  }

  nodes.forEach(node => {

    if (node.selector != undefined) {

      const selector = node.selector.replace(":host-context", "");

      if (selector.includes(":host")) {

        childFound++;

        return lookForChildren(node.nodes, childFound);

      } else {

        return lookForChildren(node.nodes, childFound);

      }

    }

  });
// This returns the wrong value so i deleted it
return childFound;
};


But it should return the childFound variable which is only return when it is greater than 1.

This function checks if a scss document contains a selector with more than one :host selector because the browser compiles it differently than expected.

When childFound is greater than one:

Expected: return childFound // Childfound is 2 or higher

Actual: childrenFound is always undefined.

Liam
  • 27,717
  • 28
  • 128
  • 190
Rowa
  • 21
  • 4

2 Answers2

1

Using for...to solved my problem. Thanks to @HarunYilmaz for pointing that out and thanks to everyone for helping me out.

Rowa
  • 21
  • 4
0

You should return value inside your function and not outside of or below that function just change position of return statement inside the last curly brace. check below code:

const plugin = stylelint.createPlugin(ruleName, isEnabled => {
  let childrenFound = 0;
  childrenFound = lookForChildren(rule.nodes, childrenFound);
  console.log(childrenFound); // Wrong Value: Always undefined
}


let lookForChildren = function(nodes, childFound) {

  if(childFound > 1) {

    console.log(childFound);

    return childFound;

  }

  nodes.forEach(node => {

    if (node.selector != undefined) {

      const selector = node.selector.replace(":host-context", "");

      if (selector.includes(":host")) {

        childFound++;

        return lookForChildren(node.nodes, childFound);

      } else {

        return lookForChildren(node.nodes, childFound);

      }

    }

  });
return childFound;
};

// This returns the wrong value so i deleted it

  • That was a typo in my code. Sorry about that. The return statement will return a wrong value. For example it should return 2 but returns 1. I'm building a for...to loop now. See if that will work – Rowa Sep 23 '19 at 09:39