Как перевести этот бит Python на идиоматический Javascript - PullRequest
1 голос
/ 02 августа 2011

Мой код на данный момент:

// The q constant of the Glicko system.
var q = Math.log(10) / 400;

function Player(rating, rd) {
    this.rating = rating || 1500;
    this.rd = rd || 200;
}

Player.prototype.preRatingRD = function(this, t, c) {
    // Set default values of t and c
    this.t = t || 1;
    this.c = c || 63.2;
    // Calculate the new rating deviation
    this.rd = Math.sqrt(Math.pow(this.rd, 2) + (Math.pow(c, 2) * t));
    // Ensure RD doesn't rise above that of an unrated player
    this.rd = Math.min(this.rd, 350);
    // Ensure RD doesn't drop too low so that rating can still change
    // appreciably
    this.rd = Math.max(this.rd, 30);
};
Player.prototype.g = function(this, rd) {
    return 1 / Math.sqrt(1 + 3 * Math.pow(q, 2) * Math.pow(rd, 2) / Math.pow(Math.PI, 2));
};
Player.prototype.e = function(this, p2rating, p2rd) {
    return 1 / (1 + Math.pow(10, (-1 * this.g(p2rd) * (this.rating - p2rating) / 400)));
};

Я работаю над реализацией JS / HTML рейтинговой системы Glicko и заимствую у pyglicko - то есть, полностью срывая его.

Это довольно короткий (вероятно, менее 100 LoC без комментариев), но у меня есть сомнения по поводу того, будет ли мой перевод работать, потому что, честно говоря, я понятия не имеюкак Javascript scoping и this на самом деле работают.Вы можете увидеть, что у меня есть по ссылке вверху.

Но, в частности, мне интересно, как бы вы выразили этот кусок кода Python в Javascript.В основном _d2 находится внутри определения класса для Player.

def _d2(self, rating_list, RD_list):
    tempSum = 0
    for i in range(len(rating_list)):
        tempE = self._E(rating_list[i], RD_list[i])
        tempSum += math.pow(self._g(RD_list[1]), 2) * tempE * (1 - tempE)
    return 1 / (math.pow(self._q, 2) * tempSum)

У меня есть функции e и g, определенные так, и q - это константа:

Player.prototype.e = function(this, ratingList, rdList) {
    // Stuff goes here
}

1 Ответ

3 голосов
/ 02 августа 2011

В Javascript вам не нужно явно передавать self (Python здесь самый странный), на самом деле)

Player.prototype.e = function(rating_list, RD_list){
    //replace "self" with "this" here:
    var tempSum = 0; //if you don't use the "var", tempSum will be a global
                     // instead of a local
    for(var i=0; i<rating_list.length; i++){ //plain old for loop - no foreach in JS
        var tempE = this._E( ... ); //note that in JS, just like in Python,
                                    //variables like this have function scope and
                                    //can be accessed outside the loop as well
        tempSum += Math.pow( ... ) //the Math namespace is always available
                                   //Javascript doesn't have a native module system
    }
    return (...);
}

Это должно работать нормально.Единственная хитрость, которую вам нужно знать о this, это то, что она очень беспорядочная.Это означает, что это определяется тем, как вы вызываете функцию:

 obj.e(); //if you do a method-like call, the this will be set to obj

Однако за кулисами не существует магической привязки.Следующее работает в python, но не работает в Javascript:

 f = obj.e
 f(); //looks like a normal function call. This doesn't point to obj
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...