Skip to content

Instantly share code, notes, and snippets.

@akanehara
Last active August 29, 2015 14:05
Show Gist options
  • Save akanehara/4b47b1dd97998c32a475 to your computer and use it in GitHub Desktop.
Save akanehara/4b47b1dd97998c32a475 to your computer and use it in GitHub Desktop.
HashMap
/**
* ハッシュ関数
*/
export interface HashFun<A> {
(o : A) : string;
}
/**
* マップ
* コンストラクタにキーのハッシュ関数を与えて使う。
* (JavaScriptは共通のオブジェクトハッシュプロトコルを持たないので、Map側でハッシュ関数を負担する)
*/
export class HashMap<K, V> {
private _ks : Object;
private _vs : Object;
private _hash : HashFun<K>;
public constructor(hash : HashFun<K>) {
this._ks = {};
this._vs = {};
this._hash = hash;
}
public has(key : K) : boolean {
return this._ks[this._hash(key)] !== undefined;
}
public get(key : K, alt : V = null) : V {
var v : V = this._vs[this._hash(key)];
return (v !== undefined) ? v : alt;
}
public put(key : K, value : V) : void {
this._ks[this._hash(key)] = key;
this._vs[this._hash(key)] = value;
}
public remove(key : K) : void {
delete this._ks[this._hash(key)];
delete this._vs[this._hash(key)];
}
public keys() : K[] {
var ks : K[] = [];
for (var h in this._ks) {
ks.push(this._ks[h]);
}
return ks;
}
public values() : V[] {
var vs : V[] = [];
for (var h in this._vs) {
vs.push(this._vs[h]);
}
return vs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment