Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
Player.prototype.d2 = function(ratingList, rdList) {
    var tempSum = 0;
    for (var i = 0; i < ratingList.length; i++) {
        var tempE = this.e(ratingList[i], rdList[i]);
        tempSum += Math.pow(this.g(rdList[i]), 2) * tempE * (1 - tempE);
    }
    return 1 / Math.pow(q, 2) * tempSum;
};

How would I accomplish the same thing in a functional paradigm?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

I think something like this will work for you.

Array.prototype.zip = function(other) {
    if (!Array.prototype.isPrototypeOf(other)) {
            throw new TypeError('Expecting an array dummy!');
    }
    if (this.length !== other.length) {
            throw new Error('Must be the same length!');
    }
    var r = [];
    for (var i = 0, length = this.length; i < length; i++) {
        r.push([this[i], other[i]]);    
    }
    return r;
};

Player.prototype.d2 = function (ratingList, rdList) {
    var self = this;
    return 1 / Math.pow(q, 2) *
        ratingList
        .zip(rdList)
        .map(function (elem) {
            var tempE = self.e(elem[0], elem[1]);
            return Math.pow(self.g(elem[1]), 2) * tempE * (1 - tempE);
        })
        .reduce(function (acc, value) {
            return acc + value;
        });
};
share|improve this answer
    
Do you actually need var self = this? I haven't had to use that anywhere else so far. –  Austin Yun Aug 5 '11 at 12:16
    
@Austin - Yes you do need it. Try removing it and see what happens. –  ChaosPandion Aug 6 '11 at 18:09
    
I'm guessing it's because inside the map function, this would refer to uh... Array.prototype? –  Austin Yun Aug 8 '11 at 16:59
    
@Austin - I believe that it will normally be the global object. –  ChaosPandion Aug 8 '11 at 17:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.