Skip to content

Instantly share code, notes, and snippets.

@ctrevarthen
Created November 24, 2015 16:12
Show Gist options
  • Save ctrevarthen/31354fdba3d2567874ed to your computer and use it in GitHub Desktop.
Save ctrevarthen/31354fdba3d2567874ed to your computer and use it in GitHub Desktop.
ShopQuick - Priorities Rule 3 Final
class PrioritiesManager : ProductManager {
static let sharedInstance = PrioritiesManager()
var productsInThisTrip : [Product]?
func addProduct(product: Product) {
let newProduct = Product(name: product.name, qty: 0)
// if the product exists
if self.doesProductExist(newProduct.name) {
// Rule #3
productsInThisTrip?.forEach({ (p: Product) -> () in
// remove the last product purchased so it can be moved
let lastProductPriority = self.findIndexForProductName(p.name)
self.removeProductWithName(p.name)
// insert the last product purchased directly above the current product
if let existingIndex = self.findIndexForProductName(newProduct.name) {
// only move products UP the priority list
self.insertProduct(p, atIndex: min(existingIndex, lastProductPriority!))
}
})
// Rule #2 - do nothing
}
else {
// if there is a last item purchased
if let lastProduct = productsInThisTrip?.last {
if let lastProductIndex = self.findIndexForProductName(lastProduct.name) {
// add the new product right after the last product purchased
self.insertProduct(newProduct, atIndex: lastProductIndex + 1) // Rule #1
}
}
else {
// just add the product to the end of the list
products.append(newProduct) // Rule #0
}
}
productsInThisTrip?.append(newProduct)
self.saveProductsToDefaults()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment