JS - Recursion examples (revealing module)

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 = (function() {
  /*************************************************************** 
  		Private members 
  ***************************************************************/
  // Some local helper functions
  var helpers = {
    invalidInt: function() {
      console.log("Starting value must be 1 or greater.");
    },
    getFirstChild: function(elem){
      var child = elem.children[0]
      if (child) {
        return child;
      } else {
        return null;
      }
    }
  };

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

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

  // Reduce an integer down to 0
  var countDown = function(count) {
    if (count > 0) {
      console.log("Starting coundown...");
      reduce(count);
    } else {
      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
  var factorial = function(num) {
  	if(num > 0){
      console.log(Factor(num));
      
      function Factor(int){
      	if(int <= 0){
        	return 1;
        } else {
        	return int * Factor(--int);
        }
      }
    } else {
    	helpers.invalidInt();
    }
  };
  
  // Collapse a multidimensional array
  var collapseArray = function(multiArr){
  	var result = multiArr[0];
  	for(var i = 1; i < multiArr.length; i++){
   ...