Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement python's namedtuple in 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?

like image 482
twneale Avatar asked Nov 28 '11 03:11

twneale


1 Answers

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.

like image 157
Jani Hartikainen Avatar answered Nov 04 '22 00:11

Jani Hartikainen