gpt4 book ai didi

javascript - 如何获得几个 immutable.js 列表的联合

转载 作者:IT老高 更新时间:2023-10-28 21:56:47 24 4
gpt4 key购买 nike

所以,我有一个列表:

let a = Immutable.List([1])

和列表 b:

let b = Immutable.List([2, 3])

我想从他们那里得到 List union === List([1, 2, 3])

我尝试 merge他们的拳头:

let union = a.merge(b); // List([2, 3])

似乎 merge 方法使用索引而不是值操作,因此用 List b 的第一项覆盖 List a 的第一项。所以,我的问题是获得多个列表联合的最简单方法是什么(最好不要迭代它们和其他额外操作)。

最佳答案

你对合并是正确的。 Merge 将使用合并列表的当前值更新索引。所以在你的情况下,你有

[0] = 1

并与

合并
[0] = 2
[1] = 3

最终用 [0]=2 覆盖 [0]=1,然后设置 [1]=3 导致合并后观察到的 [2,3] 数组。

解决这个问题的一个非常简单的方法是使用 concat

var a = Immutable.List([1]);
var b = Immutable.List([2,3]);

var c = a.concat(b);

它适用于这种情况。但是,如果情况更复杂,这可能是不正确的。例如,

var a = Immutable.List([1,4]);
var b = Immutable.List([2,3,4]);

这会给你两个 4,这在技术上不再是一个并集。不幸的是,Immutable 中没有包含联合。实现它的一种简单方法是将每个列表中的每个值设置为对象的键,然后将这些键作为结果联合。

jsFiddle Demo

function union(left,right){
//object to use for holding keys
var union = {};

//takes the first array and adds its values as keys to the union object
left.forEach(function(x){
union[x] = undefined;
});

//takes the second array and adds its values as keys to the union object
right.forEach(function(x){
union[x] = undefined;
});

//uses the keys of the union object in the constructor of List
//to return the same type we started with
//parseInt is used in map to ensure the value type is retained
//it would be string otherwise
return Immutable.List(Object.keys(union).map(function(i){
return parseInt(i,10);
}));
}

这个过程是O(2(n+m))。任何使用 containsindexOf 的进程最终都会变成 O(n^2) 所以这就是这里使用 key 的原因。

后期编辑

超高性能

function union(left,right){
var list = [], screen = {};
for(var i = 0; i < left.length; i++){
if(!screen[left[i]])list.push(i);
screen[left[i]] = 1;
}
for(var i = 0; i < right.length; i++){
if(!screen[right[i]])list.push(i);
screen[right[i]] = 1;
}
return Immutable.List(list);
}

关于javascript - 如何获得几个 immutable.js 列表的联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30126698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com