www.webdeveloper.com
Results 1 to 10 of 10

Thread: Calling a function only once

  1. #1
    Join Date
    Sep 2006
    Posts
    642

    Question Calling a function only once

    Hi

    I am trying to write a function that will generate a random number b/w 1-10 but what I also want is that the function should return the random number only once (no matter how many times we call it) unless we force it to generate it using a flag or something..I am stuck here, so please can someone help me?

    herez the code
    Code:
    var a = function(){
      	return Math.floor(Math.random() * (10 - 1) + 1); 
      
    };
    
    var b = a();
    
    console.log(b);
    JSBIN:
    http://jsbin.com/uMUhoJU/2/edit


    Thanks

  2. #2
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    240
    Code:
    var returnValue = true;
    
    var a = function() {
        var res = Math.floor(Math.random() * (10 - 1) + 1);
    
        if (returnValue == true)
        {
            returnValue = false;
            return res;
        }
        else
            return;
    };
    
    var b = a();
    console.log(b)
    Now whenever you want your function to return a number you just set your 'returnValue' variable to true.
    Last edited by tech_soul8; 09-29-2013 at 05:20 PM.

  3. #3
    Join Date
    Jun 2008
    Posts
    106
    Firstly, your output can only be 1-9 with your method. It will never return 10.

    Secondly, if you want to do it that way, you can, but the times where you don't want it to return a number, it will HAVE to return something (even if it's undefined).

    Lastly, I would use a variable outside the function to hold a boolean to determine if it should return a number or not. I'd also use the bitwise OR operator ( || ) to see if the true boolean is passed as the second argument.

    Code:
    var logFlag = true;
    var a = function (doLog) {
    
        // being explicit, for the sake of the example
        if (doLog === true || logFlag === true) {
    
            // set it to not return this again unless we pass it 'true'
            logFlag = false;
    
            return Math.floor( Math.random() * 10 ) + 1;
        }
    };
    
    var i = 0;
    while (i++ < 5) {
        // this will call the function 5 times
        // but only one number will be logged
        // (although 4 'undefined' will be logged)
        console.log( a() );
    }
    
    // then, we can log the value manually with a flag
    console.log( a(true) );

  4. #4
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,264
    The problem is to choice number without repetition ?
    Then use something like this :
    Code:
    Array.prototype.randomChoice=function(){return this.splice(Math.floor(Math.random()*this.length),1)[0]}
    
    // Use with an initial array and a current array of number (or images or objects)
    var i,arrIni=[],arrNmb=[];
    for (i=0;i<10;i++) arrIni[i]=i+1;
    
    // A function with a flag for new choices
    function newNmb(bool){
        // a copy of initial array 
       if (bool || arrNmb.length==0) arrNmb=arrIni.slice(0);
       // a random choice
       return arrNmb.randomChoice();
    }
    alert(newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb()+'\nFlag '+' '+newNmb(true)+' '+newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb())
    Last edited by 007Julien; 10-01-2013 at 07:42 AM.

  5. #5
    Join Date
    Sep 2006
    Posts
    642
    Quote Originally Posted by 007Julien View Post
    The problem is to choice number without repetition ?
    Then use something like this :
    Code:
    Array.prototype.randomChoice=function(){return this.splice(Math.floor(Math.random()*this.length),1)[0]}
    
    // Use with an initial array and a current array of number (or images or objects)
    var i,arrIni=[],arrNmb=[];
    for (i=0;i<10;i++) arrIni[i]=i+1;
    
    // A function with a flag for new choices
    function newNmb(bool){
        // a copy of initial array 
       if (bool || arrNmb.length==0) arrNmb=arrIni.slice(0);
       // a random choice
       return arrNmb.randomChoice();
    }
    alert(newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb()+'\nFlag '+' '+newNmb(true)+' '+newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb()+' '+newNmb())
    Thanks for the reply.

    I am getting this result:
    5 2 8 9 3 4
    Flag 5 4 2 9 7 6

    JSBIN: http://jsbin.com/eXizUWOH/1/edit

    It should actually give me only one randomly generated number unless I specify a flag to generate a new one.


    Thanks

  6. #6
    Join Date
    Jun 2008
    Posts
    106
    Did you try the other replies' code?...

  7. #7
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    Hi, you could do it with a closure:

    Code:
    var a = (function()
    {
    	var x;
    	function newRandom()
    	{
    		x = Math.floor(Math.random() * (10 - 1) + 1);
    	}
    	newRandom();
    	return function(v)
    	{
    		if (v) {newRandom();}
    		return x;
    	};
    }());
    
    alert(
    	a() + ' ' + a() + ' ' + a() + ' - ' + a(true) + ' ' + a() + ' ' + a()
    );
    JavaScript: Learn | Validate | Compact

  8. #8
    Join Date
    Sep 2006
    Posts
    642
    Quote Originally Posted by bionoid View Post
    Hi, you could do it with a closure:
    The term "closure" u mentioned is new to me, i tried reading it on wikipedia but what they explained didnt make any sense to me, may be because its too complicated. Could you please explain the meaning of closure in layman's terms?


    Thanks

  9. #9
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    Best description I could find with references:

    https://developer.mozilla.org/en-US/...Guide/Closures
    A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.
    When I returned a function from within my anonymous function I created a closure. Doing this creates a new dynamic scope allowing private functions and variables to be encapsulated within it.

    Code:
    var a = (function()
    {
    	var x;
    	function newRandom()
    	{
    		x = Math.floor(Math.random() * (10 - 1) + 1);
    	}
    	newRandom();
    	return function(v)
    	{
    		if (v) {newRandom();}
    		return x;
    	};
    }());
    The variable "a" has been assigned the function I returned, but still has access to all the data in its defined scope, such as "x" and "newRandom".
    JavaScript: Learn | Validate | Compact

  10. #10
    Join Date
    Sep 2006
    Posts
    642
    Great!


    Thanks for your reply.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles