admin管理员组文章数量:1405170
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 badges1 Answer
Reset to default 7You 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.
本文标签: How to implement python39s namedtuple in javascriptStack Overflow
版权声明:本文标题:How to implement python's namedtuple in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744278417a2598530.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论