real-hashmap
v1.0.1
Published
A lightweight HashMap implementation for JavaScript/TypeScript
Downloads
8
Maintainers
Readme
🗂️ Custom HashMap Implementation in TypeScript
This project provides a custom HashMap<K, V> class implemented in TypeScript.
It mimics the behavior of JavaScript’s built-in Map but with an internal hashing mechanism and bucket-based collision handling.
🚀 Features
- Supports all primitive types (
string,number,boolean,bigint,symbol,null,undefined) as keys. - Supports
objectandfunctionkeys via unique object IDs. - Automatic resize when load factor exceeds the threshold.
- Provides common map operations:
set(key, value)get(key)has(key)delete(key)clear()- Iterators:
entries(),keys(),values() forEach(callback)
- Fully typed with TypeScript generics (
HashMap<K, V>). - Implements
[Symbol.iterator]for direct iteration.
📦 Installation
Clone the repository and install dependencies:
git clone https://github.com/SadjadSadeghi/real-hashmap.git
cd real-hashmap
npm installBuild: npm run build
Usage:
import { HashMap } from "real-hashmap";
const map = new HashMap<string, number>();
map.set("apple", 1);
map.set("banana", 2);
console.log(map.get("apple")); // 1
console.log(map.has("banana")); // true
console.log(map.size); // 2
map.delete("banana");
console.log(map.has("banana")); // false
// Iterate
for (const [key, value] of map) {
console.log(key, value);
}How Keys Work
Strings: Hashed using a polynomial rolling hash.
Numbers / Booleans / BigInts: Stringified with a prefix.
Symbols: Converted to string with unique prefix.
Objects & Functions: Assigned a unique object ID using WeakMapExample:
const obj = {};
map.set(obj, "hello");
console.log(map.get(obj)); // "hello"Configuration
You can control:
initialCapacity (default: 16)
loadFactor (default: 0.75)
const customMap = new HashMap<number, string>(32, 0.5);Testing
We use Jest for unit testing.
Install types if missing:
npm i --save-dev jest @types/jest ts-jest
Run tests:
npm test