Skip to content

Instantly share code, notes, and snippets.

@brehaut
Last active October 14, 2016 02:55
Show Gist options
  • Save brehaut/6ef3550b8f6473fe49f276db148b650e to your computer and use it in GitHub Desktop.
Save brehaut/6ef3550b8f6473fe49f276db148b650e to your computer and use it in GitHub Desktop.
A primative Map class that accepts value-like objects as keys
type Hashcode = number;
interface IHashable {
hashcode(): Hashcode;
equals(o: IHashable): boolean;
}
type Association<K extends IHashable, V> = [K, V];
class ValueMap<K extends IHashable, V> {
private hashtable = new Map<Hashcode, Association<K, V>[]>();
private getBucket(h: Hashcode): Association<K, V>[] {
if (!this.hashtable.has(h)) this.hashtable.set(h, []);
return this.hashtable.get(h);
}
public set(k: K, v: V) {
const bucket = this.getBucket(k.hashcode());
for (let i = 0, j = bucket.length; i < j; i++) {
const assoc = bucket[i];
if (assoc[0].equals(k)) {
assoc[1] = v;
return;
}
}
bucket.push([k, v]);
}
public get(k: K): V|undefined {
const bucket = this.getBucket(k.hashcode());
for (let i = 0, j = bucket.length; i < j; i++) {
const [ak, v] = bucket[i];
if (ak.equals(k)) {
return v;
}
}
return undefined;
}
public has(k: K): boolean {
const bucket = this.getBucket(k.hashcode());
for (let i = 0, j = bucket.length; i < j; i++) {
const [ak, v] = bucket[i];
if (ak.equals(k)) {
return true;
}
}
return false;
}
public delete(k: K): void {
const bucket = this.getBucket(k.hashcode());
for (let i = 0, j = bucket.length; i < j; i++) {
const [ak, _] = bucket[i];
if (ak.equals(k)) {
bucket.splice(i, 1);
return;
}
}
return;
}
}
// a super dumb pair class for testing it out. worst hashcode function ever
class Pair implements IHashable {
constructor(private x: number, private y: number) { }
public hashcode():number {
return (this.x * this.y) % Number.MAX_SAFE_INTEGER;
}
public equals(o: IHashable) {
if (!(o instanceof Pair)) return false;
return o.x === this.x && o.y === this.y;
}
}
function p(x, y) { return new Pair(x, y); }
const m = new ValueMap();
m.set(p(0, 0), "hello");
m.set(p(1, 0), "world");
m.set(p(0, 1), "this is dog");
m.set(p(1, 1), "quux");
alert(m.get(p(0, 1)));
m.set(p(0, 1), "baz");
alert(m.get(p(0, 1)));
m.delete(p(0, 0));
alert(m.get(p(0, 1)));
alert(m.has(p(0, 0)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment