* Updates the priority of the given element. * Adds the element if it is not in the queue. * @param {*} key the element to change * @param {number} priority new priority of the element
(key, priority)
| 76 | * @param {number} priority new priority of the element |
| 77 | */ |
| 78 | update(key, priority) { |
| 79 | const currPos = this._heap.indexOf(key) |
| 80 | // if the key does not exist yet, add it |
| 81 | if (currPos === -1) return this.push(key, priority) |
| 82 | // else update priority |
| 83 | this.priorities.set(key, priority) |
| 84 | const parentPos = getParentPosition(currPos) |
| 85 | const currPriority = this._getPriorityOrInfinite(currPos) |
| 86 | const parentPriority = this._getPriorityOrInfinite(parentPos) |
| 87 | const [child1Pos, child2Pos] = getChildrenPositions(currPos) |
| 88 | const child1Priority = this._getPriorityOrInfinite(child1Pos) |
| 89 | const child2Priority = this._getPriorityOrInfinite(child2Pos) |
| 90 | |
| 91 | if (parentPos >= 0 && parentPriority > currPriority) { |
| 92 | this._shiftUp(currPos) |
| 93 | } else if (child1Priority < currPriority || child2Priority < currPriority) { |
| 94 | this._shiftDown(currPos) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | _getPriorityOrInfinite(position) { |
| 99 | // Helper function, returns priority of the node, or Infinite if no node corresponds to this position |
no test coverage detected