UNPKG

cachly

Version:

Type-safe, production-ready in-memory cache system for Node.js and TypeScript with advanced features.

101 lines 3.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PartitioningUtil = void 0; class PartitioningUtil { constructor(config) { this.partitions = new Map(); this.config = config; this.initializePartitions(); } initializePartitions() { for (let i = 0; i < this.config.partitions; i++) { this.partitions.set(i, { id: i, keyCount: 0, memoryUsage: 0, hitRate: 0, }); } } getPartition(key) { if (!this.config.enabled) return 0; let partitionKey; if (this.config.partitionKey) { partitionKey = this.config.partitionKey(key); } else { partitionKey = key; } switch (this.config.strategy) { case 'hash': return this.hashPartition(partitionKey); case 'range': return this.rangePartition(partitionKey); case 'custom': return this.customPartition(partitionKey); default: return this.hashPartition(partitionKey); } } hashPartition(key) { let hash = 0; for (let i = 0; i < key.length; i++) { const char = key.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; // Convert to 32-bit integer } return Math.abs(hash) % this.config.partitions; } rangePartition(key) { const firstChar = key.charAt(0).toLowerCase(); const charCode = firstChar.charCodeAt(0); return charCode % this.config.partitions; } customPartition(key) { // Custom partitioning logic - can be extended return this.hashPartition(key); } updatePartitionStats(partitionId, keyCount, memoryUsage, hitRate) { const partition = this.partitions.get(partitionId); if (partition) { partition.keyCount = keyCount; partition.memoryUsage = memoryUsage; partition.hitRate = hitRate; } } getPartitionInfo(partitionId) { return this.partitions.get(partitionId); } getAllPartitions() { return Array.from(this.partitions.values()); } getPartitionDistribution() { const distribution = {}; for (const partition of this.partitions.values()) { distribution[partition.id] = partition.keyCount; } return distribution; } getBalancedPartition() { let minKeys = Infinity; let selectedPartition = 0; for (const partition of this.partitions.values()) { if (partition.keyCount < minKeys) { minKeys = partition.keyCount; selectedPartition = partition.id; } } return selectedPartition; } isBalanced() { const keyCounts = Array.from(this.partitions.values()).map(p => p.keyCount); const avg = keyCounts.reduce((sum, count) => sum + count, 0) / keyCounts.length; const variance = keyCounts.reduce((sum, count) => sum + Math.pow(count - avg, 2), 0) / keyCounts.length; const standardDeviation = Math.sqrt(variance); // Consider balanced if standard deviation is less than 20% of average return standardDeviation < avg * 0.2; } } exports.PartitioningUtil = PartitioningUtil; //# sourceMappingURL=Partitioning.js.map