UNPKG

hash-bc

Version:

A easy Hash Table for JavaScript

80 lines (68 loc) 1.8 kB
const HashItem = require('./HashItem'); class Hash { constructor(length) { this.data = new Array(length); this.length = length || 0; } _hashHandler(key) { let counter = 0; for (let i = 0; i < key.length; i++) { counter += key.charCodeAt(i); } return counter % this.length; } setItem(key, value) { const position = this._hashHandler(key); const item = new HashItem(key, value); if (this.data[position] !== undefined) { const existsTheSameItem = this.data[position].filter((value) => value.key === key)[0]; if (!existsTheSameItem) { this.data[position].push(item); } else { console.warn(`The key ${key} already exist`); return { completed: false, item: item, }; } } else { this.data[position] = [item]; } return { completed: true, item: item, }; } getItem(key) { const position = this._hashHandler(key); if (typeof value === 'object') { return this.data[position].filter((value) => value.key === key) || undefined; } else { console.error(`The key: ${key} doesn't exist`); return undefined; } } getKeys() { const keys = []; this.data.map((value) => { if (typeof value === 'object') { value.map((value) => keys.push(value.key)); } }); return keys; } deleteItem(key) { const position = this._hashHandler(key); if (typeof this.data[position] === 'object') { this.data[position].map((value, index) => { if (value.key === key) { return this.data[position].splice(index, 1); } }); } else { console.error(`The key: ${key} doesn't exist`); return undefined; } } } module.exports = Hash;