Overly verbose simple recursion in javascript and php

notes and quirk solutions found over time
Post Reply
darknkreepy3#
Site Admin
Posts: 247
Joined: Tue Oct 27, 2009 9:33 pm

Overly verbose simple recursion in javascript and php

Post by darknkreepy3# »

So, this is a very detailed and overly verbose example of how to do recursive function calls in basic javascript. You will notice that the base is 2, which really means in this example of a number to a power (^) that we are already a X^1...

So...
2^1=2, we will start there, and reduce -- by one in a loop. The scope of javascript allows globals to enter a function but not the other way around (even obviously recursively).

Notice that there is a RETURN when calling the nested function... it is a bit odd but it basically in this case does nothing, and only the very last RETURN sends the total amount to the external variable _finalAmt. There are many ways to do this, I was just showing how to send information from a function to it's cloned version of itself in javascript. By no means is this the best or only way to do this. It's a bit heavy handed, and nested functions versus maybe a LOOP are about 3x as slow honestly. I saw this on a facebook group question and just illustrated it super over the top.

Javascript Version

Code: Select all

<script>
	//
	console.log("recursion with ^ power");
	//
	//consider this 2^1
	var _total=2;
	var _exponent=8;
	var _base=2;
	
	var cStr="";
	
	var _finalAmt=0;
	//
	function power(sent_base,sent_total,sent_exponent)
		{
		console.log("f-power ["+sent_base+"]["+sent_total+"]["+(_exponent-sent_exponent+1)+"]");
		//
		if(sent_exponent==1)
			{
			console.log("[the end]"+sent_total);
			return sent_total;
			}
		else
			{
			sent_exponent--;
			sent_total=sent_total*sent_base;
			return power(sent_base,sent_total,sent_exponent);
			}
		}
	
	_finalAmt=power(_base,_total,_exponent);
	console.log(_base+"^"+_exponent+"="+_finalAmt);
</script>
PHP Version

Code: Select all

<?php
	//
	echo "recursion with ^ power  <br />";
	//
	//consider this 2^1
	$_total=2;
	$_exponent=8;
	$_base=2;
	
	$cStr="";
	
	$_finalAmt=0;
	//
	function power($sent_base,$sent_total,$sent_exponent)
		{
		echo "f-power [".$sent_base."][".$sent_total."][".($_exponent-$sent_exponent+1)."] </br>";
		//
		if($sent_exponent==1)
			{
			echo "[the end]".$sent_total."<br />";
			return $sent_total;
			}
		else
			{
			$sent_exponent--;
			$sent_total=$sent_total*$sent_base;
			return power($sent_base,$sent_total,$sent_exponent);
			}
		}
	
	$_finalAmt=power($_base,$_total,$_exponent);
	echo $_base."^".$_exponent."=".$_finalAmt."<br />";
?>
Post Reply