JS - Recursion examples

by Zacc206

HTML

<!-- Place a needle in a haystack-->
<div id="haystack">
  <div>
    <div>
      <div>
        <div>
          <div id="needle"></div>
        </div>
      </div>
    </div>
  </div>
</div>

JavaScript

console.clear();

var Examples = {
	// Some local helper functions
	helpers: {
  	invalidInt: function(){
    	console.log("Starting value must be 1 or greater.");
    }
  },

	// Recursively search children for a div#needle elem
  haystack: function() {
    var haystack = document.getElementById('haystack');
    console.log(FindNeedle(haystack));

    function FindNeedle(elem) {
      if (elem.id === "needle") {
        return "Needle found!";
      } else if (getFirstChild(elem) === null) {
        return "Just hay."
      } else {
        return FindNeedle(getFirstChild(elem));
      }
    }

    function getFirstChild(elem) {
      var child = elem.children[0]
      if (child) {
        return child;
      } else {
        return null;
      }
    }
  },
  // Reduce an integer down to 0
  countDown: function(count){
  	if(count > 0){
    	console.log("Starting coundown...");
    	reduce(count);
    } else {
    	this.helpers.invalidInt();
    }
    
    function reduce(count){
    	console.log(count);
      if(count > 0){
      	reduce(--count);
      } else {
      	console.log("Blastoff!!");
      }
    }
  },
  // Calculate a the factorial result of an integer
  factorial: function(int){
  	if(int > 0){
    
    } else {
    	this.helpers.invalidInt();
    }
  }
};

//Examples.haystack();
//Examples.countDown(5);
//Examples.countDown(99);
Examples.countDown(0);