Skip to content

Commit

Permalink
fix(common): fixed the _.filter clone to not create sparse arrays
Browse files Browse the repository at this point in the history
Closes #1563
  • Loading branch information
christopherthielen committed Nov 21, 2014
1 parent e9f8b8a commit 750f5cf
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,10 +189,12 @@ function pluck(collection, key) {
}

function filter(collection, callback) {
var result = isArray(collection) ? [] : {};
var array = isArray(collection);
var result = array ? [] : {};
forEach(collection, function(val, i) {
if (callback(val, i))
result[i] = val;
if (callback(val, i)) {
result[array ? result.length : i] = val;
}
});
return result;
}
Expand Down
15 changes: 15 additions & 0 deletions test/commonSpec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
describe('_-like filter', function() {
it("should filter arrays", function() {
var input = [ 1, 2, 3, 4, 5 ];
var filtered = filter(input, function(int) { return int > 2; });
expect(filtered.length).toBe(3);
expect(filtered).toEqual([ 3, 4, 5 ]);
});

it("should filter objects", function() {
var input = { foo: 1, bar: 2, baz: 3, qux: 4 };
var filtered = filter(input, function(val, key) { return val > 2; });
expect(Object.keys(filtered).length).toBe(2);
expect(filtered).toEqual({ baz: 3, qux: 4 });
});
});

0 comments on commit 750f5cf

Please sign in to comment.