Skip to content

Instantly share code, notes, and snippets.

@Caleb-T-Owens
Created June 14, 2022 10:57
Show Gist options
  • Save Caleb-T-Owens/c50bb26c098fd2e1087443899f01b437 to your computer and use it in GitHub Desktop.
Save Caleb-T-Owens/c50bb26c098fd2e1087443899f01b437 to your computer and use it in GitHub Desktop.
class MemoryNode {
deleted: boolean = false // using this to indicate if the node has been deallocated
ownershipReferences: MemoryNode[] = []
ownershipReferees: MemoryNode[] = []
references: MemoryNode[] = []
referees: MemoryNode[] = []
addReference(node: MemoryNode) {
this.references.push(node)
node.addReferee(this)
}
addReferee(node: MemoryNode) {
this.referees.push(node)
}
giveOwnership(node: MemoryNode) {
this.ownershipReferences.push(node)
node.addOwnershipReferee(this)
}
addOwnershipReferee(node: MemoryNode) {
this.ownershipReferees.push(node)
}
deref(node: MemoryNode) {
this.referees = this.referees.filter((referee) => referee !== node)
}
tryDeallocate(visited: MemoryNode[] = []) {
// If there are no ownership referees, we need to try to deallocate the structure
if (this.ownershipReferees.length === 0) {
let success = true
this.references.forEach((reference) => {
if (!visited.includes(reference)) {
visited.push(reference)
let output = reference.tryDeallocate(visited)
if (!output) {
success = false
}
}
})
if (success) {
this.deleted = true
this.references.forEach((reference) => reference.deref(this))
this.references = []
return true
}
}
return false
}
derefOwnership(node: MemoryNode) {
this.ownershipReferees = this.ownershipReferees.filter((referee) => referee !== node)
this.tryDeallocate()
}
deallocate() {
this.ownershipReferences.forEach((reference) => reference.derefOwnership(this))
this.ownershipReferences = []
this.deleted = true
}
}
const fn = new MemoryNode()
const a = new MemoryNode()
const b = new MemoryNode()
fn.giveOwnership(a)
fn.giveOwnership(b)
a.addReference(b)
b.addReference(a)
fn.deallocate()
console.log(fn)
console.log(a)
console.log(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment