ConsistentHash API
Constructor
typescript
new ConsistentHash(config?: Partial<HashConfig>)Parameters
| Param | Type | Default | Description |
|---|---|---|---|
| config.virtualNodes | number | 150 | Number of virtual nodes per physical node |
Methods
getNode(key: string): HashNode | null
Find the node responsible for a key.
typescript
const node = hash.getNode("user:123");
console.log(node?.id); // "node-1"addNode(node: HashNode): void
Add a node to the hash ring.
typescript
hash.addNode({ id: "node-3" });removeNode(nodeId: string): void
Remove a node from the hash ring.
typescript
hash.removeNode("node-1");getKeyDistribution(): Map<string, number>
Get the number of keys per node.
typescript
const distribution = hash.getKeyDistribution();
console.log(distribution);
// Map { "node-0" => 365, "node-1" => 346, "node-2" => 289 }getRingSize(): number
Get the total number of virtual nodes on the ring.
typescript
const size = hash.getRingSize();
console.log(size); // 450 (3 nodes × 150 virtual nodes)hasNode(nodeId: string): boolean
Check if a node exists on the ring.
typescript
if (hash.hasNode("node-0")) {
// node exists
}getNodes(): HashNode[]
Get all physical nodes on the ring.
typescript
const nodes = hash.getNodes();
console.log(nodes); // [{ id: "node-0" }, { id: "node-1" }, ...]Interfaces
HashNode
typescript
interface HashNode {
id: string;
}HashConfig
typescript
interface HashConfig {
virtualNodes: number; // default: 150
}