Skip to content

Instantly share code, notes, and snippets.

@cramforce
Created December 30, 2011 16:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cramforce/1540475 to your computer and use it in GitHub Desktop.
Save cramforce/1540475 to your computer and use it in GitHub Desktop.
var seed = Math.random() + '';
/**
* Call this early in your program and only once and only if you are
* paranoid about the amount of entropy in Math.random().
*/
exports.srand = function(newSeed) {
seed = newSeed + '';
}
exports.create = function() {
return new SaferHash();
}
function SaferHash() {
var storage = {};
this.g = this.get = function(key) {
key = seed + key;
return storage[key];
};
this.s = this.set = function(key, val) {
key = seed + key;
storage[key] = val;
return this;
};
this.contains = function(key) {
key = seed + key;
return key in storage;
};
this.keys = function() {
return Object.keys(storage).map(function(key) {
return key.substring(seed.length);
});
};
this.delete = function(key) {
key = seed + key;
return delete storage[key];
}
this.toJSON = function() {
var self = this;
return this.keys().map(function(key) {
var val = self.get(key);
return [key, val];
});
}
this.toUnsafeObject = function() {
var self = this;
var obj = {};
this.keys().forEach(function(key) {
var val = self.get(key);
obj[key] = val;
});
return obj;
}
}
// Tests
(function() {
var saferHash = exports;
var hash = saferHash.create();
is('val', hash.set('key', 'val').get('key'));
is('val', hash.s('key', 'val').g('key'));
ok(hash.contains('key'));
ok(!hash.contains('DoesNotContain'));
is(1, hash.keys().length);
is('key', hash.keys()[0]);
is(JSON.stringify([['key', 'val']]), JSON.stringify(hash));
var unsafe = hash.toUnsafeObject();
is(JSON.stringify({'key': 'val'}), JSON.stringify(unsafe));
hash.delete('key');
is(0, hash.keys().length);
hash.s('foo', 'bar').s('key', 'val');
ok(hash.contains('foo'));
ok(hash.contains('key'));
ok(!hash.contains('bar'));
is(2, hash.keys().length);
var keys = hash.keys();
if (keys[0] == 'foo') {
is(keys[1], 'key');
}
else if (keys[0] == 'key') {
is(keys[1], 'foo');
} else {
ok(false);
}
})();
// Test functions
function ok(val) {
if (val) {
console.log("OK");
} else {
console.log("NOT OK")
}
}
function is(expected, result) {
ok(expected === result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment