Last active
January 21, 2019 08:07
-
-
Save OneCent01/7a6ea101e35cf628e0edce5b1f6a98ad to your computer and use it in GitHub Desktop.
Javascript implementation of an insert value method for hashtables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
HashTable.prototype.add = function(key, value) { | |
var index = key.hashCode(); | |
var tuple = [key, value]; | |
var bucket = this._storage.get(index); | |
if (bucket) { | |
for (var i = 0; i < bucket.length; i++) { | |
if (bucket[i][0] === key) { | |
bucket[i][1] = value; | |
} else { | |
bucket.push(tuple); | |
} | |
} | |
} else { | |
this._storage.set(index, [tuple]); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a bug in this code, when a
bucket
is found at givenindex
you iterate overbucket
check for currentkey
, if you find akey
than you updatevalue
and keep iterating overbucket
and ifkey
is not found you pushtuple
in array and keep iterating, for each iteration if nokey
is foundtuple
will be pushed to array...It should be like this.