<script>
function HashSet() {
this._arr = new Array();
}
HashSet.prototype.add = function(e) {
var arr = this._arr;
var i = arr.indexOf(e);
if (i == -1) arr.push(e);
}
HashSet.prototype.get = function(i) {
return this._arr[i];
}
HashSet.prototype.size = function(i) {
return this._arr.length;
}
HashSet.prototype.remove = function(e) {
var arr =this._arr;
var i = arr.indexOf(e);
if (i != -1) arr.splice(i, 1);
}
HashSet.prototype.toString = function() {
return this._arr.join(',');
}
/*
var startTime = new Date();
var set = new HashSet();
for(i = 0; i < 10004; i++) { //it took 3 seconds to do; with 100000 elements, my browser hangs
set.add('Index ' + i); // value also effect to time complete task
}
set.add('One');
set.add('Two');
set.add('Three');
set.add('Four');
set.add('Five');
set.add('One');//will be ignored
set.add('One');//will be ignored
set.remove('Five');
var finishTime = new Date();
document.write(startTime + '<hr />' + set.size() + ' distinct eles<hr />' + finishTime);
document.close();
*/
var a = [1, 2, 3, 4, 5];
function MyIntSet(n) {
this.N = n;
this._partitions = new Array();
var i;
for (i = 0; i < n; i++) {
this._partitions[i] = new HashSet();
}
}
MyIntSet.prototype.add = function(e) {
// e Object - y = f(e) - y Int
// assume that e is alreay Int
var iP = e % this.N;
var set = this._partitions[iP];
set.add(e);
}
MyIntSet.prototype.get = function(i) {
return -1;
}
MyIntSet.prototype.size = function(i) {
var r = 0;
for (i = 0; i < this.N; i++) {
r += this._partitions[i].size();
}
return r;
}
MyIntSet.prototype.remove = function(e) {
var iP = e % this.N;
var set = this._partitions[iP];
set.remove(e);
}
MyIntSet.prototype.toString = function() {
var r = '';
for (i = 0; i < this.N; i++) {
var pi = this._partitions[i].toString();
if (pi != '') r = r + pi + ',';
}
if (r != '') r = r.substring(0, r.length - 1);
return r;
}
var startTime = new Date();
var xset = new MyIntSet(5000);
for(i = 0; i < 1000000; i++) {
xset.add(i);
xset.add(i); // will be ignored
}
document.write(startTime + '<hr />' + xset.size() + ' elements<hr />' + new Date());
document.close();
/*
var arr = new Array();
for (i = 0; i < 5000000; i++) {
arr.push(i);
}
document.write(startTime + '<hr />' + arr.length + ' elements<hr />' + new Date());
document.close();
*/
</script>
Title:
HashSet implementation in Javascript
Description:
<script> function HashSet() { this._arr = new Array(); } HashSet.prototype.add = function(e) { var arr = this._arr; ...
...
Rating:
4