Created
February 18, 2021 01:23
-
-
Save kenkawakenkenke/206f58ac1f37891e3f2f2591784acf5b to your computer and use it in GitHub Desktop.
Solution for the XOR list coding quiz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// XOR list coding quiz solution | |
class Memory { | |
constructor() { | |
this.memory = {}; | |
this.pointerAccumulator = 100; | |
} | |
alloc() { | |
const pointer = this.pointerAccumulator++; | |
const obj = { | |
pointer, | |
value: {} | |
}; | |
this.memory[pointer] = obj; | |
return obj; | |
} | |
dereference(pointer) { | |
if (!this.memory[pointer]) { | |
throw new Error("dereferenced non-existence memory location:" + pointer); | |
} | |
return this.memory[pointer]; | |
} | |
} | |
const memory = new Memory(); | |
class XorList { | |
constructor(memory) { | |
this.memory = memory; | |
const headNode = memory.alloc(); | |
const tailNode = memory.alloc(); | |
headNode.value = { | |
both: 0 ^ tailNode.pointer, | |
payload: "HEAD", | |
}; | |
tailNode.value = { | |
both: 0 ^ headNode.pointer, | |
payload: "TAIL", | |
}; | |
this.headPointer = headNode.pointer; | |
this.tailPointer = tailNode.pointer; | |
} | |
add(obj) { | |
let newNodeRef = this.memory.alloc(); | |
newNodeRef.value.payload = obj; | |
const tailNodeRef = this.memory.dereference(this.tailPointer); | |
// pprev, prev(pprev^tail), tail(prev^0) | |
// pprev, prev(pprev^new), new(prev^tail), tail(new^0) | |
const tailPointer = this.tailPointer; | |
const prevPointer = tailNodeRef.value.both; | |
const prevNodeRef = this.memory.dereference(prevPointer); | |
const pprevPointer = prevNodeRef.value.both ^ tailPointer; | |
const newPointer = newNodeRef.pointer; | |
prevNodeRef.value.both = pprevPointer ^ newPointer; | |
newNodeRef.value.both = prevPointer ^ tailPointer; | |
tailNodeRef.value.both = newPointer ^ 0; | |
} | |
get(index) { | |
let prevPointer = 0; | |
let currentPointer = this.headPointer; | |
// prev, current(prev^next), next | |
for (let i = 0; i <= index; i++) { | |
const currentNodeRef = this.memory.dereference(currentPointer); | |
let nextPointer = prevPointer ^ currentNodeRef.value.both; | |
prevPointer = currentPointer; | |
currentPointer = nextPointer; | |
} | |
return memory.dereference(currentPointer).value.payload; | |
} | |
} | |
const ref = memory.alloc(); | |
const list = new XorList(memory); | |
list.add("fish"); | |
list.add("cod"); | |
list.add("salmon"); | |
console.log(list.get(0)); // fish | |
console.log(list.get(1)); // cod | |
console.log(list.get(2)); // salmon |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment