Sei corretto per l'unione. Unisci aggiornerà l'indice con il valore corrente della lista di fusione. Quindi nel tuo caso hai avuto
[0] = 1
e incorporato con
[0] = 2
[1] = 3
che ha finito per sovrascrivere [0]=1
con [0]=2
, e quindi impostare [1]=3
conseguente vostro osservato [2,3]
matrice dopo la fusione.
Un approccio molto semplice per risolvere questo sarebbe quello di utilizzare concat
var a = Immutable.List([1]);
var b = Immutable.List([2,3]);
var c = a.concat(b);
E funzionerà per questa situazione. Tuttavia, se la situazione è più complessa, potrebbe essere errata. Ad esempio,
var a = Immutable.List([1,4]);
var b = Immutable.List([2,3,4]);
questo ti darebbe due 4 che non è tecnicamente più un sindacato. Sfortunatamente non c'è unione inclusa in Immutable. Un modo semplice per implementarlo sarebbe impostare ciascun valore in ogni elenco come chiave per un oggetto e quindi prendere quei tasti come unione risultante.
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);
}));
}
Questo processo è O(2(n+m))
. Qualsiasi processo che usi contains
o indexOf
finirà per essere O(n^2)
quindi è per questo che le chiavi sono state utilizzate qui.
ritardo modificare
Hyper-performante
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);
}
fonte
2015-05-08 16:14:58
Stai cercando 'a.concat (b)'? – loganfsmyth
@loganfsmyth God dammed, non notarlo nel doc) Grazie. puoi incollarlo come risposta in modo che io possa accettarlo. –
Lmao, anche io non ho visto concat .. ho provato un sacco di cose .. grazie :) – Spock