如何将这部分Python转换为惯用的Javascript

How to translate this bit of Python to idiomatic Javascript

本文关键字:Javascript 转换 这部分 Python      更新时间:2023-09-26

我的代码:

// 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)));
};

我正在做一个Glicko评级系统的JS/HTML实现,我大量借鉴了pyglicko——也就是说,完全抄袭了它。

这是相当短的(可能少于100 LoC没有评论),但我有我的疑虑,我的翻译是否会工作,因为老实说,我不知道Javascript范围和this实际上是如何工作的。你可以看到我在顶部的链接。

但具体来说,我想知道你将如何在Javascript中表达这一点Python代码。基本上,_d2Player的类定义中。

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)

我已经得到了函数eg这样定义,q是一个常数:

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

在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