@gabrielrufino/cube
Version:
Data structures made in Typescript
84 lines (83 loc) • 3.1 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var HashTable = /** @class */ (function () {
function HashTable(inputs, _a) {
if (inputs === void 0) { inputs = {}; }
var _b = _a === void 0 ? {} : _a, _c = _b.maxSize, maxSize = _c === void 0 ? 100 : _c;
this._data = Array.from({ length: maxSize });
this.maxSize = maxSize;
for (var _i = 0, _d = Object.entries(inputs); _i < _d.length; _i++) {
var _e = _d[_i], key = _e[0], value = _e[1];
this.put(key, value);
}
}
Object.defineProperty(HashTable.prototype, "data", {
get: function () {
return this._data
.map(function (value, index) { return ({ index: index, value: value }); })
.filter(function (_a) {
var value = _a.value;
return value !== undefined;
})
.reduce(function (accumulator, current) {
var _a;
return (__assign(__assign({}, accumulator), (_a = {}, _a[current.index] = current.value, _a)));
}, {});
},
enumerable: false,
configurable: true
});
Object.defineProperty(HashTable.prototype, "size", {
get: function () {
return Reflect.ownKeys(this.data).length;
},
enumerable: false,
configurable: true
});
HashTable.prototype.put = function (key, value) {
var position = this._hashCode(key);
this._data[position] = value;
return value;
};
HashTable.prototype.get = function (key) {
var position = this._hashCode(key);
return this.data[position] || null;
};
HashTable.prototype.remove = function (key) {
var value = this.get(key);
var position = this._hashCode(key);
Reflect.deleteProperty(this._data, position);
return value;
};
HashTable.prototype._hashCode = function (key) {
var code = key
.split('')
.map(function (character) { return character.charCodeAt(0); })
.reduce(function (previous, current) { return previous + current; }, 0);
return code % this.maxSize;
};
HashTable.prototype[Symbol.toPrimitive] = function (type) {
var primitives = {
default: true,
number: this.size,
string: "[ ".concat(Object.entries(this.data).map(function (_a) {
var key = _a[0], value = _a[1];
return "".concat(key, " => ").concat(value);
}).join(', '), " ]"),
};
return primitives[type];
};
return HashTable;
}());
exports.default = HashTable;