0

I asked this before, but a little vague and poorly worded.

I have a object that takes in Actions and puts them into a stack that it goes through over time. It performs the first Action in the stack until it's done, then it performs the second, and so on. There is a RepeatAction that can take in an array of other Actions and perform them a number of times in a similar fashion. (.repeat() simply puts a new RepeatAction into the objects stack.

Take this for example:

object.repeat(10,[new LogAction(Math.random())]);

Given that LogAction only takes in a parameter and logs it out. When the object's repeat function gets called it will put 10 LogActions into its stack, but they will all log the same number. What I'm looking for is a way that it will log a different number all 10 times.

You may say just pass in Math.random as a function, but then what if I want to pass in 4 * Math.random()?

Any help?

Evan Ward
  • 1,371
  • 2
  • 11
  • 23
  • 1
    You could define some kind of chaining thing on `Action`s and build ones for basic operators, e.g. `new LogAction(times(4).of(new Action(Math.random)))`. Or maybe not; I’m still not sure what an `Action` is supposed to represent. – Ry- Jun 24 '14 at 21:17

3 Answers3

2

You may say just pass in Math.random as a function,

Yes, I would.

but then what if I want to pass in 4 * Math.random()?

Then in place of Math.random, use

function() { return 4 * Math.random(); }
Matt
  • 20,108
  • 1
  • 57
  • 70
2

The code needs to invoke a function (later) to get a different value. e.g.

// pass in the `random` function - do not get a random number immediately!
object.repeat(10, [new LogAction(Math.random)])

// create and pass in a custom function that uses `random` itself
var rand4 = function () { return Math.random() * 4 }
object.repeat(10, [new LogAction(rand4)])

Since "LogAction" is not disclosed, I'll make a simple example to work with the above.

function LogAction (arg) {
    this.execute = function () {
        // If the supplied argument was a function, evaluate it
        // to get the value to log. Otherwise, log what was supplied.
        var value = (typeof arg === 'function') ? arg() : arg;
        console.log(value);                
    }
}

Reading through How do JavaScript closures work? will likely increase the appreciation of functions as first-class values, which the above relies upon.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
2

You can pass function which returns result of random:

object.repeat(10,[new LogAction(function(){return Math.random();})]);

And in LogAction function you simply need to check if argument is a function:

function LogAction(arg){
    var value = arg&& getType.toString.call(arg) === '[object Function]' ? arg() : arg;

    //log value    
}
Dmitry Zaets
  • 3,289
  • 1
  • 20
  • 33