UNPKG

@amaui/hash-table

Version:
53 lines (51 loc) 1.5 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; import { is } from '@amaui/utils'; export default class AmauiHashTable { // ASCII character code range 0-127 constructor(limit) { _defineProperty(this, "value", []); _defineProperty(this, "length", 0); _defineProperty(this, "limit", 127); if (is('number', limit) && limit > 0) this.limit = limit; this.value = new Array(this.limit); } // Override for a custom hashing method hash(property) { let value = 0; if (is('string', property)) { for (let i = 0; i < property.length; i++) value += property[i].charCodeAt(0); } return value % this.limit; } get(property) { const index = this.hash(property); const values = this.value[index] || []; return values.find(item => item[0] === property)?.[1]; } set(property, value) { const index = this.hash(property); if (!this.value[index]) this.value[index] = []; const values = this.value[index]; values.push([property, value]); this.length++; return this; } remove(property) { const index = this.hash(property); const values = this.value[index]; if (values) { const valueIndex = values.findIndex(item => item[0] === property); if (valueIndex > -1) { values.splice(valueIndex, 1); this.length--; return true; } } return false; } clear() { this.value = new Array(this.limit); this.length = 0; return this; } }