HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Custom JavaScript function queue

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptcustomqueuefunction

Problem

For fun, I made a function queue in JavaScript. I named it tinyq. You can add functions to it, and each function is passed the next function in the queue. You can also pass parameters to the functions, and they can return values.

function q(){
    var Q = [], t = this;
    this.length = 0;
    this.add = function (f){
        Q.push(f);
        this.length++;
    };
    this.run = function(){
        var n = Q.shift();
        this.length = Q.length;
        if(typeof n === 'function'){
            var a = Array.prototype.slice;
            return n.apply(window,[function(){
                return t.run.apply(t, a.call(arguments));
            }].concat(a.call(arguments)));
        }
    };
}


Here's a simple example of its use.

var Q = new q;
Q.add(function(next, A, B){
    return A + ": "+ next(B);
});
Q.add(function(next, C){
    return C + "123";
});
console.log(Q.length); // 2
console.log(Q.run("Test", "ABC")); // "Test: ABC123"


So, what do you think of my function queue? Any improvements, or anything I'm doing wrong?

P.S. I was also trying to make this small, any suggestions on making it smaller?

Solution

I'm still trying to wrap my head around what exactly is happening in that apply/call mass :-)

But that may be a hint, that those three lines aren't really well readable. I'm aware you want to keep it small, but unless the code needs to be really, really fast (which I doubt it does) I would prefer readability over shortness.

In that line, I would prefer to have long, more expressive variable names. It be better to use complete words instead of Q, t, n, a etc.

If in the end, shortness is still important, then use a JavaScript compressor.

BTW, you should keep JavaScript naming conventions in mind, too. Constructor functions ("classes") should be named with capital letters (Q instead of q) and fields should use small letters (q instead of Q).

Just out of interest: Can you give a concrete use case for this kind of queue?

Context

StackExchange Code Review Q#7735, answer score: 8

Revisions (0)

No revisions yet.