Skip to content

Instantly share code, notes, and snippets.

@rotelstift
Created November 29, 2024 09:28
Show Gist options
  • Save rotelstift/32558ead9dde818cf093905bde6fa2f7 to your computer and use it in GitHub Desktop.
Save rotelstift/32558ead9dde818cf093905bde6fa2f7 to your computer and use it in GitHub Desktop.
Typescript でオレオレ実装している Hash
interface pair {
key: string
value: any
}
type bin = Array<pair>
// オレオレ Hash 実装
// このあと Rehash を作りたい
// あと、できれば value の型は宣言時に設定したい
class MyHash {
bucket: Array<bin>
pair_count: number
constructor(size: number) {
this.bucket = new Array<bin>(size)
this.pair_count = 0
}
get_value(key: string): any {
return this.bucket[this.hash(key)].find((pair) => pair.key == key)?.value
}
set_value(key: string, value: any): void {
const pair = {key: key, value: value}
const hash = this.hash(key)
// 最初に bucket[hash] に値が入る時
if(typeof(this.bucket[hash]) === 'undefined') {
this.pair_count += 1
this.bucket[hash] = [pair]
return
}
// bucket[hash] に既に値があるが、同じキーが存在していなかった場合
let existing_pair = this.bucket[hash].find((pair) => pair.key == key)
if(typeof(existing_pair) === 'undefined') {
this.pair_count += 1
this.bucket[hash].push(pair)
return
}
// bucket[hash] に既に値があり、既存のキーがあるため値を上書きする場合
this.substitute(existing_pair, value)
}
delete(key: string): void | null {
const hash = this.hash(key)
let key_index = this.bucket[hash].findIndex((pair) => pair.key == key)
if(key_index == -1) {
return null
}
this.pair_count -= 1
this.bucket[hash].splice(key_index, 1)
if(this.bucket[hash].length == 0) {
delete this.bucket[hash]
}
}
private hash(key:string): number {
let hash_num = 0
key.split('').forEach(char => {
hash_num += char.charCodeAt(0)
});
return hash_num % this.bucket.length
}
// オブジェクトを操作すると参照渡しになるらしい。 Javascript 難しい
private substitute(pair: pair, value: any): void {
pair.value = value
}
}
// main
let hash = new MyHash(10)
hash.set_value('foo', 42)
hash.set_value('hoo', 'answer')
hash.set_value('foo', 'OK!')
console.log(hash)
console.log(hash.get_value('foo'))
console.log(hash.get_value('hoo'))
hash.delete('foo')
console.log(hash)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment