Skip to content

Commit 750f5cf

Browse files
fix(common): fixed the _.filter clone to not create sparse arrays
Closes #1563
1 parent e9f8b8a commit 750f5cf

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/common.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -189,10 +189,12 @@ function pluck(collection, key) {
189189
}
190190

191191
function filter(collection, callback) {
192-
var result = isArray(collection) ? [] : {};
192+
var array = isArray(collection);
193+
var result = array ? [] : {};
193194
forEach(collection, function(val, i) {
194-
if (callback(val, i))
195-
result[i] = val;
195+
if (callback(val, i)) {
196+
result[array ? result.length : i] = val;
197+
}
196198
});
197199
return result;
198200
}

test/commonSpec.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
describe('_-like filter', function() {
2+
it("should filter arrays", function() {
3+
var input = [ 1, 2, 3, 4, 5 ];
4+
var filtered = filter(input, function(int) { return int > 2; });
5+
expect(filtered.length).toBe(3);
6+
expect(filtered).toEqual([ 3, 4, 5 ]);
7+
});
8+
9+
it("should filter objects", function() {
10+
var input = { foo: 1, bar: 2, baz: 3, qux: 4 };
11+
var filtered = filter(input, function(val, key) { return val > 2; });
12+
expect(Object.keys(filtered).length).toBe(2);
13+
expect(filtered).toEqual({ baz: 3, qux: 4 });
14+
});
15+
});

0 commit comments

Comments
 (0)