Prototypes
In prototypes, we use function constructors to initiate.
1 2 3 4 5 |
// table is public property function HashTable() { // notice that this is public this.table = new Array(MAX); } |
Then we use prototypes to create one copy of functions to be shared by all instances of HashTable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// load factor α = num of keys to be inserted / number of slots in hash table // O(1 + α) HashTable.prototype.insert = function(data) { var index = _hash(data); if (!this.table[index]) {this.table[index] = new Queue();} this.table[index].push(data); } HashTable.prototype.search = function(data) { return this.table[_hash(data)].search(data); } HashTable.prototype.print = function() { console.log('\n\n===== print table ======='); for (var i = 0; i < this.table.length; i++) { console.log('---' + i + '---'); var bucket = this.table[i]; if (bucket) { bucket.print(); } else { console.log(`empty`); } } } module.exports = new HashTable(); |
IIFE
If you want privacy, use IFEE and closure.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// todo table is private (version with IFEE and closures) module.exports = (function HashTable() { var table = new Array(MAX); function hash(data) { console.log('using private IFEE hash function') if (typeof data !== "string") { console.log(`hash - input must be string!`); return null; } let value = 0; for (let i = 0; i < data.length; i++) { value += data[i].charCodeAt(0); // Returns the Unicode value of the character at the specified location. } return (value * data.length) % MAX; } function insertData(data) { var index = hash(data); console.log(data + ' hashed to index ' + index); if (!table[index]) {table[index] = new Queue();} table[index].push(data); } function searchData(data) { return table[hash(data)].search(data); } function printTable() { console.log('\n\n===== print table ======='); for (var i = 0; i < table.length; i++) { console.log('---' + i + '---'); var bucket = table[i]; if (bucket) { bucket.print(); } else { console.log('empty'); } } } return { print: printTable, insert: insertData, search: searchData }; })(); |