Attempt fix memory leak
This commit is contained in:
@ -12,16 +12,62 @@ class PriorityQueue<T> {
|
||||
|
||||
enqueue(item: T): void {
|
||||
this.items.push(item)
|
||||
this.items.sort(this.compare)
|
||||
this.siftUp(this.items.length - 1)
|
||||
}
|
||||
|
||||
dequeue(): T | undefined {
|
||||
return this.items.shift()
|
||||
if (this.items.length === 0) return undefined
|
||||
|
||||
const result = this.items[0]
|
||||
const last = this.items.pop()
|
||||
|
||||
if (this.items.length > 0 && last !== undefined) {
|
||||
this.items[0] = last
|
||||
this.siftDown(0)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
get length(): number {
|
||||
return this.items.length
|
||||
}
|
||||
|
||||
private siftUp(index: number): void {
|
||||
while (index > 0) {
|
||||
const parentIndex = Math.floor((index - 1) / 2)
|
||||
if (this.compare(this.items[index]!, this.items[parentIndex]!) < 0) {
|
||||
;[this.items[index], this.items[parentIndex]] = [this.items[parentIndex]!, this.items[index]!]
|
||||
index = parentIndex
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private siftDown(index: number): void {
|
||||
const length = this.items.length
|
||||
while (true) {
|
||||
let minIndex = index
|
||||
const leftChild = 2 * index + 1
|
||||
const rightChild = 2 * index + 2
|
||||
|
||||
if (leftChild < length && this.compare(this.items[leftChild]!, this.items[minIndex]!) < 0) {
|
||||
minIndex = leftChild
|
||||
}
|
||||
if (rightChild < length && this.compare(this.items[rightChild]!, this.items[minIndex]!) < 0) {
|
||||
minIndex = rightChild
|
||||
}
|
||||
|
||||
if (minIndex === index) break
|
||||
;[this.items[index], this.items[minIndex]] = [this.items[minIndex]!, this.items[index]!]
|
||||
index = minIndex
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.items = []
|
||||
}
|
||||
}
|
||||
|
||||
class CharacterMoveService extends BaseService {
|
||||
@ -144,14 +190,14 @@ class CharacterMoveService extends BaseService {
|
||||
const h = this.getDistance(neighbor, end)
|
||||
const f = g + h
|
||||
|
||||
const node: Node = {...neighbor, g, h, f, parent: current}
|
||||
const node: Node = { ...neighbor, g, h, f, parent: current }
|
||||
openList.enqueue(node)
|
||||
}
|
||||
}
|
||||
|
||||
return [] // No path found
|
||||
} finally {
|
||||
while(openList.length > 0) openList.dequeue()
|
||||
while (openList.length > 0) openList.dequeue()
|
||||
closedSet.clear()
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user