Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const HashTable = function() {
- this._limit = 8;
- this._size = 0;
- this._storage = LimitedArray(this._limit)
- }
- HashTable.prototype.insert = function(key, value) {
- let index = getIndexBelowMaxForKey(key, this._limit);
- const innerBuckets = [];
- const innerTuples = {};
- innerTuples[key] = value;
- this._size++;
- if (this._size > this._limit * 0.7) {
- this.resize(this._limit * 2)
- index = getIndexBelowMaxForKey(key, this._limit)
- }
- if (this._storage.get(index) === undefined) {
- innerBuckets.push(innerTuples)
- this._storage.set(index, innerBuckets)
- } else {
- for (let i = 0; i < this._storage.get(index).length; i++) {
- if (this._storage.get(index)[i][k]) {
- this._storage.get(index)[i][k] = v
- } else {
- this._storage.get(index).push(innerTuples)
- }
- }
- }
- }
- HashTable.prototype.retrieve = function (key) {
- const index = getIndexBelowMaxForKey(key, this._limit)
- for (let i = 0; i < this._storage.get(index).length; i++) {
- if (this._storage.get(index)[i] === undefined) {
- return undefined
- } else if (this._storage.get(index)[i][key]) {
- return this._storage.get(index)[i][key]
- }
- }
- }
- HashTable.prototype.remove = function (key) {
- let index = getIndexBelowMaxForKey(key, this._limit)
- this._size--
- if (this._size < this._limit * 0.3) {
- this.resize(this._limit / 2)
- index = getIndexBelowMaxForKey(key, this._limit)
- }
- for (let i = 0; i < this._storage.get(index).length; i++) {
- if (this._storage.get(index)[i][key]) {
- delete this._storage.get(index)[i]
- }
- }
- }
- HashTable.prototype.resize = function (newLimit) {
- this._limit = newLimit
- let oldStorage = this._storage
- this._storage = LimitedArray(this._limit)
- oldStorage.each((pairs) => {
- if (pairs) {
- for (var i = 0; i < pairs.length; i++) {
- if (pairs[i]) {
- let pair = pairs[i]
- this.insert(Object.keys(pair)[0], Object.values(pair)[0])
- this._size--
- }
- }
- }
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement