Core JavaScript

A Simple Hash Table

This is an example program that shows how to create a hash table in JavaScript.

HashTable.html

<!DOCTYPE html>
<html>
	<head>
		<title>XoaX.net's Javascript</title>
		<script type="text/javascript" src="HashTable.js"></script>
	</head>
	<body onload="Initialize()">
		<div id="idOutput1"></div>
		<div id="idOutput2"></div>
		<div id="idOutput3"></div>
		<div id="idOutput4"></div>
		<div id="idOutput5"></div>
	</body>
</html>

HashTable.js

function Initialize() {
	let qHashTable = new CHashTable(64);
	qHashTable.Put("key1", 12);
	qHashTable.Put("key2", 23);
	qHashTable.Put("key3", 34);
	qHashTable.Put("key4", 45);
	qHashTable.Put("key5", 56);
	
	let qElement1 = document.getElementById("idOutput1");
	qElement1.innerHTML = qHashTable.Get("key1");
	let qElement2 = document.getElementById("idOutput2");
	qElement2.innerHTML = qHashTable.Get("key2");
	let qElement3 = document.getElementById("idOutput3");
	qElement3.innerHTML = qHashTable.Get("key3");
	let qElement4 = document.getElementById("idOutput4");
	qElement4.innerHTML = qHashTable.Get("key4");
	let qElement5 = document.getElementById("idOutput5");
	qElement5.innerHTML = qHashTable.Get("key5");
}


class CHashTable {
	#miSize;
	#miCapacity;
	#mqValues;
	constructor(iCapacity) {
		this.mkiBase = 0x81C9DC5;
		this.mkiPrime = 0x01000193;
		this.#miSize = 0;
		this.#miCapacity = iCapacity;
		this.#mqValues = new Uint32Array(iCapacity);
	}
	#Hash(sKey) {
		let iHash = this.mkiBase;
		let iCurr = 0;
		let iLength = sKey.length;
		while (iCurr < iLength) {
			iHash ^= sKey.charAt(iCurr);
			iHash *= this.mkiPrime;
			++iCurr;
		}
		// The capacity is a power of 2. So, this just truncates the bits.
		return iHash & (this.#miCapacity - 1);
	}
	Put(sKey, qValue) {
		// Note that any conflict will be written over.
		// This could be fixed by making each entry a list.
		this.#mqValues[this.#Hash(sKey)] = qValue;
		++this.#miSize;
	}
	Get(sKey) {
		return this.#mqValues[this.#Hash(sKey)];
	}
}
 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.