I have a class object that I thought was working last night. But now I try to test out my set Hash method so I do: blah = new HashTable; and it says that HashTable isn't defined.
I have another file thats not linked here and all its variables are also showing up as undefined(in the console). I swear I got this working last night though so i'm miffed.
I'm getting an error that maybe I didn't notice before but it says
ERROR: Parsing error: The keyword 'class' is reserved class HashTable
JSLint(2) Expected an identifier and instead saw 'class'. Stopping. (4% scanned).
What am I doing wrong? Someone please help.
My desire, is just to be able to test out my javascript code in the console to make sure that everything is working. I tried google chrome's snippet and it has bugs. I tried codepen and it's a sandbox so it doesn't work properly in the console now I'm trying brackets and it's not letting me test in the console either. Getting so frustrated.
class HashTable {
constructor(size){
this.keyMap = new Array(size);
}
function _hash(key) {
let total = 0;
let prime = 31
for (let i = 0; i < Math.min(key.length, 100); i++) {
let char = key[i];
let value = char.charCodeAt(0) - 96;
total = (total * prime + value) % this.keyMap;
}
return total;
}
function set(key){
hashNumber = this._hash(key);
return hashNumber;
}
}
-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src = "app.js"></script>
<script src = "hash.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Please work</h1>
</body>
</html>
I don't know if it specifically relates to the errors you've called out or not, but your HashTable
class has syntax errors in it. You don't use function
to define the methods of a class within a class
construct. So:
class HashTable {
constructor(size){
this.keyMap = new Array(size);
}
_hash(key) {
// ^--------------------------------------- no `function` here
let total = 0;
let prime = 31
for (let i = 0; i < Math.min(key.length, 100); i++) {
let char = key[i];
let value = char.charCodeAt(0) - 96;
total = (total * prime + value) % this.keyMap;
}
return total;
}
set(key) {
// ^--------------------------------------- nor here
hashNumber = this._hash(key);
return hashNumber;
}
}
Other notes:
There's almost never any reason to use new Array
.
You're using the array you've assigned to this.keyMap
as a number in the expression total = (total * prime + value) % this.keyMap;
which doesn't make any sense.
I'd recommend calculating the upper bound of your for
loop once, and then reusing that value, rather than calculating it on every loop iteration.