Home > Software design >  I need help understanding this recursive function (eloquent Javascript Chapter 14)
I need help understanding this recursive function (eloquent Javascript Chapter 14)

Time:11-05

This recursive function looks for the passed argument (string) in an HTML format. In this case the string “book”. The function answers true.

<!doctype html>
<html>
  <head>
    <title>My home  page</title>
  </head>
  <body>
    <h1>My home page</h1>
    <p>Hello, I am Marijn and this is my home page.</p>
    <p>I also wrote a book!  Read it
      <a href="http://eloquentjavascript.net">here</a>.</p>
  </body>
</html>
<script>
function talksAbout(node, string) {
   
  if (node.nodeType == Node.ELEMENT_NODE) {
    for (let child of node.childNodes) { 
      if (talksAbout(child, string)) {
        return true;
      }
    }
    return false;
  } else if (node.nodeType == Node.TEXT_NODE) {
    return node.nodeValue.indexOf(string) > -1;
  }
}

console.log(talksAbout(document.body, "book"));

// true

Now if I delete the "book" from the HTML, the function still returns true.

<!doctype html>
<html>
  <head>
    <title>My home  page</title>
  </head>
  <body>
    <h1>My home page</h1>
    <p>Hello, I am Marijn and this is my home page.</p>
    <p>I also wrote a !  Read it
      <a href="http://eloquentjavascript.net">here</a>.</p>
  </body>
</html>
<script>
function talksAbout(node, string) {
   
  if (node.nodeType == Node.ELEMENT_NODE) {
    for (let child of node.childNodes) { 
      if (talksAbout(child, string)) {
        return true;
      }
    }
    return false;
  } else if (node.nodeType == Node.TEXT_NODE) {
    return node.nodeValue.indexOf(string) > -1;
  }
}

console.log(talksAbout(document.body, "book"));

//true

CodePudding user response:

It's because the last condition you hit is right before you return true. Open the console and run the code below to see it in action. The irony being that by passing the entire body in you're capturing the console.log that is searching for book. Neat!

function talksAbout(node, string) {

  if (node.nodeType == Node.ELEMENT_NODE) {
    for (let child of node.childNodes) {
      if (talksAbout(child, string)) {
        console.warn("let's give them something to talk about! True!", node, string);
        return true;
      }
    }
    console.warn("Return false!");
    return false;
  } else if (node.nodeType == Node.TEXT_NODE) {
    console.warn("nodeValue!", node.nodeValue.indexOf(string), string);
    return node.nodeValue.indexOf(string) > -1;
  }
}

console.log(talksAbout(document.body, "book"));
<html>

<head>
  <title>My home page</title>
</head>

<body>
  <h1>My home page</h1>
  <p>Hello, I am Marijn and this is my home page.</p>
  <p>I also wrote a ! Read it
    <a href="http://eloquentjavascript.net">here</a>.</p>
</body>

</html>

  • Related