Test your recursive knowledge

User avatar
agibsonsw
SilverLounger
Posts: 2403
Joined: 05 Feb 2010, 22:21
Location: London ENGLAND

Test your recursive knowledge

Post by agibsonsw »

Hello. (JavaScript)

I have a function (similar to the following) that I would like to accept either a number or an array of numbers as an argument:

Code: Select all

function DoubleThem(num) {
    while (num.length) DoubleThem(num.pop());
    if ( typeof num == 'undefined' || isNaN(num) ) return;
    window.alert(num * 2);
}
But it ends up trying to double an undefined, or non-existent, value/object.

Andy.
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.

User avatar
Jezza
5StarLounger
Posts: 847
Joined: 24 Jan 2010, 06:35
Location: A Magic Forest in Deepest, Darkest, Kent

Re: Test your recursive knowledge

Post by Jezza »

Andrew I haven't tested this but have you tried:

Code: Select all

function DoubleThem(num) 
{
    while (num.length) DoubleThem(num.pop());
    {
    if ( typeof num == 'undefined' || isNaN(num) ) return false;
    }
else
   {
    window.alert(num * 2);
   }
}
Jerry
I’ll be more enthusiastic about encouraging thinking outside the box when there’s evidence of any thinking going on inside it

User avatar
agibsonsw
SilverLounger
Posts: 2403
Joined: 05 Feb 2010, 22:21
Location: London ENGLAND

Re: Test your recursive knowledge

Post by agibsonsw »

Thanks for getting back to me.

I tried something similar with 'undefined' but it didn't work. I think the sticking point is an empty array, which is not undefined.
The following works perfectly:

Code: Select all

while ( col.length ) AddSortByNumber(tbl,col.pop());
if ((col instanceof Array) || isNaN(col)) return;
//this is the actual name of my procedure
I like this method - it's neater than checking for an array or number and then looping through the array. There is an overhead with recursion
but this procedure works with table columns and there will never be a huge number of them.

Thanks again, Andy.

(P.S. it's nice to have an example of recursion which isn't a Edited: Fibonacci series :smile: )
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.