如何在javascript中实现python的namedtuple

发布于 2024-12-18 10:37:38 字数 430 浏览 5 评论 0原文

我将如何在javascript中实现python的namedtuple?理想情况下,我还想要一个可以“映射”序列序列的函数,将其转换为类似命名元组的对象序列。

// with underscore.js included...
var points = [[1,2], [3,4], [4,5]
var Point = namedlist('Point', 'x y')
points = _.map(Point._make, points)

point1 = points[0]
var x = point1.x
var y = point1.y

请注意,我不想每次都编写像“Point”这样的新类,而是希望有一个工厂函数来生成一个支持使用给定字段名称访问列表项的新类。

旁注:这个问题的一个假设是 javascript 映射使用的内存较少。这个假设合理吗?

How would I go about implementing python's namedtuple in javascript? Ideally I would also want a function I could "map" over a sequence of sequences to turn it into a sequence of namedtuple-like objects.

// with underscore.js included...
var points = [[1,2], [3,4], [4,5]
var Point = namedlist('Point', 'x y')
points = _.map(Point._make, points)

point1 = points[0]
var x = point1.x
var y = point1.y

Note that I don't want to have to code a new class like "Point" every time, but instead would like a factory function that produces a new class supporting list item access with the given field names.

Side note: an assumption underlying this question is that javascript maps use less memory that lists. Is that assumption reasonable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见终念 2024-12-25 10:37:38

你可以只使用类似的东西

var namedlist = function(fields) {
    return function(arr) {
        var obj = { };

        for(var i = 0; i < arr.length; i++) {
            obj[fields[i]] = arr[i];            
        }

        return obj;
    };
};

//use:
var points = [[1,2], [3,4], [5,6]];
var Point = namedlist(['x', 'y']);

points = _.map(Point, points);

//Single item:
var pt = Point([1,2]);

至于内存使用,这取决于底层 JS 引擎如何实现每个构造。我怀疑数组比对象消耗更少的内存,但简单对象(如这里)和数组之间的差异可能不是很显着。

You could just use something like

var namedlist = function(fields) {
    return function(arr) {
        var obj = { };

        for(var i = 0; i < arr.length; i++) {
            obj[fields[i]] = arr[i];            
        }

        return obj;
    };
};

//use:
var points = [[1,2], [3,4], [5,6]];
var Point = namedlist(['x', 'y']);

points = _.map(Point, points);

//Single item:
var pt = Point([1,2]);

As for memory usage, it depends on how the underlying JS engine implements each construct. My suspicion is that an array will consume less memory than an object, but the difference between simple objects (like here) and arrays is probably not very significant.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文