Javascript hash code example
Example 1: javascript hash string
function hashFnv32a(str, asString, seed) {
var i, l,
hval = (seed === undefined) ? 0x811c9dc5 : seed;
for (i = 0, l = str.length; i < l; i++) {
hval ^= str.charCodeAt(i);
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
}
if( asString ){
return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
}
return hval >>> 0;
}
Example 2: java script hash
function hashFnv32a(str, asString, seed) {
var i, l,
hval = (seed === undefined) ? 0x811c9dc5 : seed;
for (i = 0, l = str.length; i < l; i++) {
hval ^= str.charCodeAt(i);
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
}
if( asString ){
return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
}
return hval >>> 0;
}
Example 3: js hash table example
var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);
Example 4: js hash table example
Hash = function(oSource){
for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey];
};
Hash.prototype = Object.create(null);
var oHash = new Hash({foo: 'bar'});
oHash.foo === 'bar';
oHash['foo'] === 'bar';
oHash['meow'] = 'another prop';
oHash.hasOwnProperty === undefined;
Object.keys(oHash);
oHash instanceof Hash;
Example 5: How to use hash in javascript
var h = new Object();
h['one'] = 1;
h['two'] = 2;
h['three'] = 3;
for (var k in h) {
if (h.hasOwnProperty(k)) {
alert('key is: ' + k + ', value is: ' + h[k]);
}
}
Example 6: How to use hash in javascript
function HashTable(obj)
{
this.length = 0;
this.items = {};
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
this.items[p] = obj[p];
this.length++;
}
}
this.setItem = function(key, value)
{
var previous = undefined;
if (this.hasItem(key)) {
previous = this.items[key];
return previous;
}
else {
this.length++;
}
this.items[key] = value;
return previous;
}
this.getItem = function(key) {
return this.hasItem(key) ? this.items[key] : undefined;
}
this.hasItem = function(key)
{
return this.items.hasOwnProperty(key);
}
this.removeItem = function(key)
{
if (this.hasItem(key)) {
previous = this.items[key];
this.length--;
delete this.items[key];
return previous;
}
else {
return undefined;
}
}
this.keys = function()
{
var keys = [];
for (var k in this.items) {
if (this.hasItem(k)) {
keys.push(k);
}
}
return keys;
}
this.values = function()
{
var values = [];
for (var k in this.items) {
if (this.hasItem(k)) {
values.push(this.items[k]);
}
}
return values;
}
this.each = function(fn) {
for (var k in this.items) {
if (this.hasItem(k)) {
fn(k, this.items[k]);
}
}
}
this.clear = function()
{
this.items = {}
this.length = 0;
}
}