Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions orderBook.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
function reconcileOrder(existingBook, incomingOrder) {
const oppOrderTypes = existingBook.filter(order => order.type !== incomingOrder.type)
let updatedBook = existingBook.filter(order => order.type === incomingOrder.type)
updatedBook = oppOrderTypes.length

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're gonna short circuit on the existingBook.length you should do that before you start filtering.

? updatedBook.concat(determineSamePrice(oppOrderTypes, incomingOrder))
: updatedBook.concat(incomingOrder)
return updatedBook
}
Comment on lines +1 to +8

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you dealt with one order at a time you wouldn't need so many loops. You're filtering twice here and then later doing a findIndex. See the solution branches.


const determineSamePrice = (existingBook, incomingOrder) => {
let index = incomingOrder.type === 'sell' ? existingBook.findIndex(order => order.price >= incomingOrder.price)
: existingBook.findIndex(order => order.price <= incomingOrder.price)
return index >= 0 ? determineSameQuantity(existingBook, incomingOrder, index)
: existingBook.concat(incomingOrder)
}

const determineSameQuantity = (existingBook, incomingOrder, index) => {
if (existingBook[index].quantity === incomingOrder.quantity) {
existingBook.splice(index, 1)
return existingBook
}
else if (existingBook[index].quantity > incomingOrder.quantity) {
existingBook[index].quantity -= incomingOrder.quantity
return existingBook
}
else if (existingBook[index].quantity < incomingOrder.quantity) {
incomingOrder.quantity -= existingBook[index].quantity
existingBook.splice(index, 1)
return determineSamePrice(existingBook, incomingOrder)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You've got flow of control split out across multiple functions which is why this code becomes so unreadable. It also makes debugging much harder. reconcileOrder should be responsible for flow of control with the other functions merely operating on and returning data for it.

}
}


module.exports = reconcileOrder
Loading