add #buildLookup method to turn collection in to a fast lookup hash

implement #without in terms of it
add tests and internal docs
This commit is contained in:
Mike Frawley
2010-02-17 10:12:22 -06:00
parent 1b1943b0ca
commit 263b1ee92d
3 changed files with 28 additions and 3 deletions

View File

@@ -230,6 +230,24 @@
_.size = function(obj) {
return _.toArray(obj).length;
};
// Build a lookup map from a collection.
// Pay a little memory upfront to make searching a collection for a
// value faster later
// e.g:
//
// var lookup = _.buildLookup([1,2,8]) // {1: true, 2: true, 8: true}
// lookup[key] // instead of: _.include(array, key)
//
// See example usage in #without
// By default sets the value to true, can pass in a value to use instead
_.buildLookup = function (obj, useValue) {
useValue = (useValue === undefined)? true : useValue;
return _.reduce(obj, {}, function (memo, value) {
memo[value] = useValue;
return memo;
});
};
// -------------------------- Array Functions: ------------------------------
@@ -269,8 +287,8 @@
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
var values = _.rest(arguments);
return _.select(array, function(value){ return !_.include(values, value); });
var lookup = _.buildLookup(_.rest(arguments));
return _.filter(array, function(value){ return !lookup[value]; });
};
// Produce a duplicate-free version of the array. If the array has already