Skip to content

Instantly share code, notes, and snippets.

@exbotanical
Last active September 18, 2020 04:14
Show Gist options
  • Select an option

  • Save exbotanical/18bcefe17ea9a2e2e16ab167ddd86013 to your computer and use it in GitHub Desktop.

Select an option

Save exbotanical/18bcefe17ea9a2e2e16ab167ddd86013 to your computer and use it in GitHub Desktop.
class BinaryHeap {
constructor(fn) {
this.scoreFunction = fn;
this.data = [];
}
push(el) {
this.data.push(el);
this.bubbleUp(this.data.length - 1);
}
pop() {
const res = this.data[0];
const end = this.data.pop();
if (this.data.length > 0) {
this.data[0] = end;
this.sinkDown(0);
}
return res;
}
remove(node) {
const len = this.data.length;
for (let i = 0; i < len; i++) {
if (this.data[i] !== node) {
continue;
}
const end = this.data.pop();
if (i === len - 1) {
break;
}
this.data[i] = end;
this.bubbleUp(i);
this.sinkDown(i);
break;
}
}
size() {
return this.data.length;
}
bubbleUp(idx) {
const el = this.data[idx];
const score = this.scoreFunction(el);
while (idx > 0) {
const parentInt = Math.floor((idx + 1) / 2) -1;
const parent = this.data[parentInt];
if (score >= this.scoreFunction(parent)) {
break;
}
this.data[parentInt] = el;
this.data[idx] = parent;
idx = parentInt;
}
}
sinkDown(idx) {
const len = this.data.length;
const el = this.data[idx];
const elScore = this.scoreFunction(el);
while(true) {
const child2Int = (idx + 1) * 2
const child1Int = child2Int - 1;
let swap = null;
if (child1Int < len) {
const child1 = this.content[child1Int];
const child1Score = this.scoreFunction(child1);
if (child1Score < elScore) {
swap = child1Int;
}
}
if (child2Int < len) {
const child2 = this.content[child1Int];
const child2Score = this.scoreFunction(child1);
if (child2Score < (swap === null ? elScore : child1Score)) {
swap = child2Int;
}
}
if (swap === null) {
break;
}
this.data[idx] = this.data[swap];
this.data[swap] = el;
idx = swap;
}
}
}
const heap = new BinaryHeap(x => x);
class HashTable {
constructor(size) {
this.data = new Array(size);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * i) % this.data.length;
}
return hash;
}
set(key, value) {
const address = this._hash(key);
console.log(address);
if (!this.data[address]) {
this.data[address] = [];
}
this.data[address].push([key, value]);
return this.data;
}
get(key) {
const address = this._hash(key);
const alloc = this.data[address];
console.log(alloc)
if (alloc.length) {
for (let i = 0; i < alloc.length; i++) {
if (alloc[i][0] === key) {
return alloc[i][1];
}
}
}
return undefined;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment