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

Commit f8c4216

Browse files
Martin R. Hufskypetebacondarwin
Martin R. Hufsky
authored andcommitted
feat(filterFilter): compare object with custom toString() to primitive
Closes #10464 Closes #10548
1 parent 4501da3 commit f8c4216

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/ng/filter/filter.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@
5454
* - `false|undefined`: A short hand for a function which will look for a substring match in case
5555
* insensitive way.
5656
*
57+
* Primitive values are converted to strings. Objects are not compared against primitives,
58+
* unless they have a custom `toString` method (e.g. `Date` objects).
59+
*
5760
* @example
5861
<example>
5962
<file name="index.html">
@@ -156,6 +159,10 @@ function filterFilter() {
156159
};
157160
}
158161

162+
function hasCustomToString(obj) {
163+
return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
164+
}
165+
159166
// Helper functions for `filterFilter`
160167
function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
161168
var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
@@ -165,8 +172,8 @@ function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
165172
comparator = equals;
166173
} else if (!isFunction(comparator)) {
167174
comparator = function(actual, expected) {
168-
if (isObject(actual) || isObject(expected)) {
169-
// Prevent an object to be considered equal to a string like `'[object'`
175+
if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
176+
// Should not compare primitives against objects, unless they have custom `toString` method
170177
return false;
171178
}
172179

test/ng/filter/filterSpec.js

+23
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,29 @@ describe('Filter: filter', function() {
472472
});
473473

474474

475+
it('should consider custom `toString()` in non-strict comparison', function() {
476+
var obj = new Date(1970, 0);
477+
var items = [{test: obj}];
478+
expect(filter(items, '1970').length).toBe(1);
479+
expect(filter(items, 1970).length).toBe(1);
480+
481+
obj = {};
482+
obj.toString = function() { return 'custom'; };
483+
items = [{test: obj}];
484+
expect(filter(items, 'custom').length).toBe(1);
485+
});
486+
487+
488+
it('should not throw on missing `toString()` in non-strict comparison', function() {
489+
var obj = Object.create(null);
490+
var items = [{test: obj}];
491+
expect(function() {
492+
filter(items, 'foo');
493+
}).not.toThrow();
494+
expect(filter(items, 'foo').length).toBe(0);
495+
});
496+
497+
475498
it('as equality when true', function() {
476499
var items = ['misko', 'adam', 'adamson'];
477500
var expr = 'adam';

0 commit comments

Comments
 (0)