Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

feat(filterFilter): compare object with custom toString() to primitive #10548

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/ng/filter/filter.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@
* - `false|undefined`: A short hand for a function which will look for a substring match in case
* insensitive way.
*
* Primitive values are converted to strings. Objects are not compared against primitives,
* unless they have a custom `toString` method (e.g. `Date` objects).
*
* @example
<example>
<file name="index.html">
Expand Down Expand Up @@ -159,8 +162,10 @@ function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
comparator = equals;
} else if (!isFunction(comparator)) {
comparator = function(actual, expected) {
if (isObject(actual) || isObject(expected)) {
// Prevent an object to be considered equal to a string like `'[object'`
if (isObject(expected) ||
isObject(actual) &&
(actual.toString === Object.prototype.toString || !isFunction(actual.toString))) {
// Should not compare primitives against objects, unless they have custom `toString` method
return false;
}

Expand Down
23 changes: 23 additions & 0 deletions test/ng/filter/filterSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,29 @@ describe('Filter: filter', function() {
});


it('should consider custom `toString()` in non-strict comparison', function() {
var obj = new Date(1970, 0);
var items = [{test: obj}];
expect(filter(items, '1970').length).toBe(1);
expect(filter(items, 1970).length).toBe(1);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm...these tests failed on some browsers (Chrome 39 on OS X). The failures are probably related to locale.
Changing new Date(0) to new Date(1970, 0) should fix the issue.

Alternatively, you could change 0 to 86400000 to ensure or timezones are in 1970, but I prefer the former approach.


obj = {};
obj.toString = function() { return 'custom'; };
items = [{test: obj}];
expect(filter(items, 'custom').length).toBe(1);
});


it('should not throw on missing `toString()` in non-strict comparison', function() {
var obj = Object.create(null);
var items = [{test: obj}];
expect(function() {
filter(items, 'foo');
}).not.toThrow();
expect(filter(items, 'foo').length).toBe(0);
});


it('as equality when true', function() {
var items = ['misko', 'adam', 'adamson'];
var expr = 'adam';
Expand Down