最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to implement python's namedtuple in javascript - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Nov 28, 2011 at 3:25 twnealetwneale 2,9465 gold badges29 silver badges37 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论