Skip to content

Instantly share code, notes, and snippets.

@pricklywiggles
Created January 21, 2021 22:39
Show Gist options
  • Save pricklywiggles/257ff877e793dc1d95b304b34a1bd35f to your computer and use it in GitHub Desktop.
Save pricklywiggles/257ff877e793dc1d95b304b34a1bd35f to your computer and use it in GitHub Desktop.
Casidoo-179
// Our HashMap can have up to 5077 entries
const MAX_INDEX = 5077;
// helpers
let isMultipleOf = k => n => n%k === 0
let isMultipleOfFour = isMultipleOf(4);
// hash function for strings using 4 char word folding
let hash = s => {
let total = 0;
let charMultiplier = 1;
for (let i=0; i<s.length; i++) {
total += s.charCodeAt(i) * charMultiplier;
charMultiplier = isMultipleOfFour(i+1) ? charMultiplier = 1 : charMultiplier * 256;
}
return total % MAX_INDEX;
}
// Our HashMap class, lacks error handling.
class HashMap {
constructor() {
this.hashMap = [];
}
get(k) {
return (this.hashMap[hash(k)] ?? [])[1]
}
put(k,v) {
this.hashMap[hash(k)] = [k,v]
}
remove(k) {
this.hashMap[hash(k)] = undefined
}
print() {
let output = "\n{\n"
this.hashMap.forEach(([k, v] = []) => output += ` ${k}: ${v},\n`)
output += "}\n"
console.log(output)
}
}
let m = new HashMap();
let add = (x,y) => x+y
m.put("alice", "Some value for alice")
m.put("add", add)
m.put("myHashMap", new HashMap)
m.get("add")
m.get("myHashMap").put("bob", "Bob's Burgers")
m.put("bobby", m.get("myHashMap").get("bob"))
m.print()
/* OUTPUT:
"
{
myHashMap: [object Object],
alice: Some value for alice,
bobby: Bob's Burgers,
add: (x, y) => x + y,
}
"
/*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment