I wrote a extender function to observableArray in knockout js. What I'm looking for is a way to extract the intersection records based on one property. This works well on smaller number of arrays, but shows pretty poor performance in larger arrays. I dont know if it is the observables that makes it slower?
How would you guys write it?
obsArray2 - The array to compare with
Key - Name of the property to compare between
ko.observableArray.fn.intersect = function (obsArray2, Key) {
var self = Enumerable.From(ko.unwrap(this));
var arrValues1 = self.Select(function (item) { return ko.unwrap(item[Key]); });
arrValues2 = Enumerable.From(ko.unwrap(obsArray2)).Select(function (item) { return ko.unwrap(item[Key]); });
var IntersectedValues = arrValues1.Intersect(arrValues2).ToArray();
return self.Where(function (item) { return IntersectedValues.contains(ko.unwrap(item[Key])) }).ToArray();
return obsArray1.Intersect(obsArray2).ToArray();
};
1 Answer 1
I would not use linq.js for anything time sensitive, it is known to be slow, definitely compared to just using old skool for
loops and arrays. Which is what I would use.
Other than, if I were to write this, I would consider naming some thing differently:
obsArray2
->observableArray
, there is noobsArray1
, and it was not clear at first if obs means there are objects in the array or it is an observable arrays.self
-> anything butself
which usually refers tothis
, perhapsenum1
?arrValues1
really contains anEnumerable
which is not really an array, confusing, I would perhaps have chosenset1
because in maths, intersections are made of sets orenum1
because that is what the variable type is- Same for
arrValues2
of course intersectedValues
-> I would have gone for simplyintersection
Furthermore,
- You have 2
return
statements, there can be only one - It seems silly to go back to
self
and filter out only elements that are in the intersection, can't you build the return value fromintersectedValues
?
-
\$\begingroup\$ Thank you. Naming variables is a skill i really lack. Thank you for great pointers! What would you use linqjs for? Smaller tasks? \$\endgroup\$Pochen– Pochen2014年12月05日 08:40:58 +00:00Commented Dec 5, 2014 at 8:40
-
\$\begingroup\$ I would use linqjs for complex operations with little volume. \$\endgroup\$konijn– konijn2014年12月05日 15:34:49 +00:00Commented Dec 5, 2014 at 15:34