@amaui/hash-table
Version:
58 lines (57 loc) • 1.78 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@amaui/utils");
class AmauiHashTable {
constructor(limit) {
this.value = [];
this.length = 0;
// ASCII character code range 0-127
this.limit = 127;
if ((0, utils_1.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 ((0, utils_1.is)('string', property)) {
for (let i = 0; i < property.length; i++)
value += property[i].charCodeAt(0);
}
return value % this.limit;
}
get(property) {
var _a;
const index = this.hash(property);
const values = this.value[index] || [];
return (_a = values.find(item => item[0] === property)) === null || _a === void 0 ? void 0 : _a[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;
}
}
exports.default = AmauiHashTable;