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

Commit c157a25

Browse files
author
Martin R. Hufsky
committed
feat(filterFilter): compare object with custom toString() to primitive
Closes #10464
1 parent 9e6161e commit c157a25

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/ng/filter/filter.js

+7-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">
@@ -159,8 +162,10 @@ function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
159162
comparator = equals;
160163
} else if (!isFunction(comparator)) {
161164
comparator = function(actual, expected) {
162-
if (isObject(actual) || isObject(expected)) {
163-
// Prevent an object to be considered equal to a string like `'[object'`
165+
if (isObject(expected) ||
166+
isObject(actual) &&
167+
(actual.toString === Object.prototype.toString || !isFunction(actual.toString))) {
168+
// Should not compare primitives against objects, unless they have custom `toString` method
164169
return false;
165170
}
166171

test/ng/filter/filterSpec.js

+23
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,29 @@ describe('Filter: filter', function() {
375375
});
376376

377377

378+
it('should consider custom `toString()` in non-strict comparison', function() {
379+
var obj = new Date(1970, 0);
380+
var items = [{test: obj}];
381+
expect(filter(items, '1970').length).toBe(1);
382+
expect(filter(items, 1970).length).toBe(1);
383+
384+
obj = {};
385+
obj.toString = function() { return 'custom'; };
386+
items = [{test: obj}];
387+
expect(filter(items, 'custom').length).toBe(1);
388+
});
389+
390+
391+
it('should not throw on missing `toString()` in non-strict comparison', function() {
392+
var obj = Object.create(null);
393+
var items = [{test: obj}];
394+
expect(function() {
395+
filter(items, 'foo');
396+
}).not.toThrow();
397+
expect(filter(items, 'foo').length).toBe(0);
398+
});
399+
400+
378401
it('as equality when true', function() {
379402
var items = ['misko', 'adam', 'adamson'];
380403
var expr = 'adam';

0 commit comments

Comments
 (0)