Skip to content

Commit

Permalink
Support values implementing HasEquals in HashMap.hashCode() (#48)
Browse files Browse the repository at this point in the history
Added failing test for "should generate hashCodes for values implementing HasEquals"

Generate hashCodes for values implementing HasEquals
  • Loading branch information
Vera van Mondfrans authored Nov 27, 2020
1 parent 20fb3fc commit 2fb35c8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/HashMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ export class HashMap<K,V> implements IMap<K,V> {
hashCode(): number {
return this.hamt.fold(
(acc: number, value: V, key: K & WithEquality) =>
acc + fieldsHashCode([key, value]), 0);
acc + fieldsHashCode(key, value), 0);
}

/*
Expand Down
22 changes: 21 additions & 1 deletion tests/HashMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { LinkedList } from "../src/LinkedList";
import { Option } from "../src/Option";
import { Stream } from "../src/Stream";
import { Tuple2 } from "../src/Tuple2";
import { fieldsHashCode } from "../src/Comparison";
import { fieldsHashCode, HasEquals, getHashCode } from "../src/Comparison";
import { MyClass} from "./SampleData";
import { assertFailCompile } from "./TestHelpers";
import * as assert from 'assert'
Expand Down Expand Up @@ -152,6 +152,26 @@ describe("hashmap equality", () => {
it("should not have trivial hashcode collisions #2", () =>
assert.equal(false, HashMap.of(["48", 1], ["49", 2], ["50", 3], ["51", 4]).hashCode()
== HashMap.of(["49345678", 2], ["50", 3], ["51", 4]).hashCode()));
it("should generate hashCodes for values implementing HasEquals", () => {
class TestClass implements HasEquals {
constructor(
public value: string
) {}

public equals(other: unknown): boolean {
return this.hashCode() === getHashCode(other);
}

public hashCode(): number {
return fieldsHashCode(this.value)
}
}

const a = HashMap.of(["48", new TestClass("foo")]).hashCode();
const b = HashMap.of(["48", new TestClass("bar")]).hashCode();

assert.equal(false, a == b);
});
})

describe("hashmap - toString should be nicely formatted", () => {
Expand Down

0 comments on commit 2fb35c8

Please sign in to comment.