Skip to content

Commit 431b645

Browse files
committed
Use Map shim with _.uniq
1 parent f77e099 commit 431b645

File tree

1 file changed

+54
-10
lines changed

1 file changed

+54
-10
lines changed

underscore.js

Lines changed: 54 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,55 @@
131131
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
132132
};
133133

134+
// A small Map shim, to support the most basic use cases.
135+
var Map = (function() {
136+
var keyer = function(value) {
137+
return typeof value === 'string' ? 's' + value : value;
138+
};
139+
var Map = function() {
140+
this._values = [];
141+
this._keys = [];
142+
this._primitives = nativeCreate && nativeCreate(null);
143+
this.size = 0;
144+
145+
this._lastKey = void 0;
146+
this._lastIndex = -1;
147+
};
148+
Map.prototype.get = function(key) {
149+
if (this.has(key)) return this._values[this._lastIndex];
150+
};
151+
Map.prototype.has = function(key) {
152+
var index = this._indexOf(key);
153+
return index >= 0 && index < this.size;
154+
};
155+
Map.prototype.set = function(key, value) {
156+
var index = this._indexOf(key);
157+
158+
this._values[index] = value;
159+
if (index >= this.size) {
160+
this.size = index + 1;
161+
this._keys[index] = key;
162+
if (this._primitives && !_.isObject(key)) this._primitives[keyer(key)] = index;
163+
}
164+
};
165+
Map.prototype._indexOf = function(key) {
166+
var index = this._lastIndex;
167+
if (this._lastKey === key && index >= 0) return index;
168+
if (this._primitives && !_.isObject(key)) {
169+
index = this._primitives[keyer(key)];
170+
} else {
171+
index = _.indexOf(this._keys, key);
172+
}
173+
if (index === -1 || index === void 0) index = this.size;
174+
175+
this._lastKey = key;
176+
this._lastIndex = index;
177+
return index;
178+
};
179+
return Map;
180+
})();
181+
182+
134183
// Collection Functions
135184
// --------------------
136185

@@ -518,21 +567,16 @@
518567
isSorted = false;
519568
}
520569
if (iteratee != null) iteratee = cb(iteratee, context);
521-
var result = [];
522-
var seen = [];
570+
var seen = new Map();
571+
var result = seen._values;
523572
for (var i = 0, length = array.length; i < length; i++) {
524573
var value = array[i],
525574
computed = iteratee ? iteratee(value, i, array) : value;
526575
if (isSorted) {
527-
if (!i || seen !== computed) result.push(value);
576+
if (seen !== computed) result.push(value);
528577
seen = computed;
529-
} else if (iteratee) {
530-
if (!_.contains(seen, computed)) {
531-
seen.push(computed);
532-
result.push(value);
533-
}
534-
} else if (!_.contains(result, value)) {
535-
result.push(value);
578+
} else if (!seen.has(computed)) {
579+
seen.set(computed, value);
536580
}
537581
}
538582
return result;

0 commit comments

Comments
 (0)