Skip to content

Correctly handle hashing of objects that return non-objects from valueOf() #1654

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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
24 changes: 24 additions & 0 deletions __tests__/issues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,27 @@ describe('Issue #1293', () => {
expect(secondState).toEqual(firstState);
});
});

describe('Issue #1643', () => {
[
['a string', 'test'],
['a number', 5],
['null', null],
['undefined', undefined],
['a boolean', true],
['an object', {}],
['an array', []],
['a function', () => null],
].forEach(([label, value]) => {
class MyClass {
valueOf() {
return value;
}
}

it(`Collection#hashCode() should handle objects that return ${label} for valueOf`, () => {
const set = Set().add(new MyClass());
set.hashCode();
});
});
});
7 changes: 4 additions & 3 deletions src/Hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import { smi } from './Math';
const defaultValueOf = Object.prototype.valueOf;

export function hash(o) {
if (o && o.valueOf !== defaultValueOf && typeof o.valueOf === 'function') {
o = o.valueOf();
}

switch (typeof o) {
case 'boolean':
// The hash values for built-in constants are a 1 value for each 5-byte
Expand All @@ -31,9 +35,6 @@ export function hash(o) {
// Drop any high bits from accidentally long hash codes.
return smi(o.hashCode(o));
}
if (o.valueOf !== defaultValueOf && typeof o.valueOf === 'function') {
o = o.valueOf(o);
}
return hashJSObj(o);
case 'undefined':
return 0x42108423;
Expand Down