1
var getNumberOfBacklogOrders = function (orders) {2
const buyHeap = new Heap((child, parent) => child.price > parent.price);3
const sellHeap = new Heap((child, parent) => child.price < parent.price);5
for (let [price, amount, orderType] of orders) {8
// while there are amount to be decremented from the sell,9
// orders to in the buy backlog, and the price of the largest10
// price is greater than the sell price decrement the11
// amount of the order with the largest price by the amount12
while (amount > 0 && buyHeap.peak() && buyHeap.peak().price >= price) {13
if (buyHeap.peak().amount > amount) {14
buyHeap.peak().amount -= amount;17
amount -= buyHeap.pop().amount;21
// if there is any amount left, add it to the sale backlog23
sellHeap.push({ price, amount });28
// while there are amount to be decremented from the buy,29
// orders to in the sell backlog, and the price of the smallest30
// price is less than the buy price decrement the31
// amount of the order with the smallest price by the amount32
while (amount > 0 && sellHeap.peak() && sellHeap.peak().price <= price) {33
if (sellHeap.peak().amount > amount) {34
sellHeap.peak().amount -= amount;37
amount -= sellHeap.pop().amount;41
// if there is any amount left, add it to the buy backlog43
buyHeap.push({ price, amount });48
// total all of the amounts in both backlogs and return the result49
let accumultiveAmount = 0;50
for (const { amount } of buyHeap.store) {51
accumultiveAmount += amount;53
for (const { amount } of sellHeap.store) {54
accumultiveAmount += amount;56
return accumultiveAmount % 1000000007;70
return this.store.length;74
if (this.store.length < 2) {75
return this.store.pop();77
const result = this.store[0];78
this.store[0] = this.store.pop();85
this.heapifyUp(this.store.length - 1);90
const parent = Math.floor((child - 1) / 2);91
if (this.shouldSwap(child, parent)) {92
[this.store[child], this.store[parent]] = [103
heapifyDown(parent) {105
let [child, child2] = [1, 2]106
.map((x) => parent * 2 + x)107
.filter((x) => x < this.size());108
if (this.shouldSwap(child2, child)) {111
if (this.shouldSwap(child, parent)) {112
[this.store[child], this.store[parent]] = [123
shouldSwap(child, parent) {124
return child && this.fn(this.store[child], this.store[parent]);