Skip to content

Instantly share code, notes, and snippets.

import UIKit
public class PaymentProcessor {
// Variable Declaration
fileprivate var batchSum : Double!
private var queue: Queue<Double>!
private let BATCH_CAP: Double!
private var defaults: UserDefaults!
private func shouldProcessBatch() -> Bool{
//1
guard batchSum < BATCH_CAP else {
return true
}
return false
}
@Mreyna3
Mreyna3 / contents.swift
Created May 26, 2019 20:28
enqueue function
public func enqueue(transaction: Double){
if(shouldProcessBatch()){
//1
processBatch()
addToBatch(transaction: transaction)
}else{
//2
addToBatch(transaction: transaction)
}
}
@Mreyna3
Mreyna3 / contents.swift
Last active May 26, 2019 20:49
addToBatch
private func addToBatch(transaction: Double) {
// 1
queue.enqueue(element: transaction)
//2
batchSum += transaction
if(shouldProcessBatch()){
// 3
processBatch()
}else{
@Mreyna3
Mreyna3 / contents.swift
Created May 26, 2019 21:22
processBatch
func processBatch(){
// 1
for _ in 0..<queue.getCount(){
// 2
batchSum -= queue.peek()!
print("deueuing \(queue.dequeue()!)")
}
print("deueuing \(batchSum!)")
// 3
@Mreyna3
Mreyna3 / contents.swift
Created May 26, 2019 21:40
resetBatchSum function
func resetBatchSum(){
//1
batchSum = 0.0
//2
defaults.set(batchSum, forKey: "batch_sum")
}
@Mreyna3
Mreyna3 / contents.swift
Last active June 7, 2019 11:28
Test Data
var transactionsDataSource1 = [0.32,0.10,0.01,0.02]
var processor = PaymentProcessor()
for i in 0..<transactionsDataSource1.count {
processor.enqueue(transaction: transactionsDataSource1[i])
}
let sum = processor.batchSum
print(sum)
@Mreyna3
Mreyna3 / contents.swift
Last active June 6, 2019 05:02
format extension
public extension Double {
func format() -> String{
let formatter = NumberFormatter()
formatter.numberStyle = .currency
let formattedDouble = formatter.string(from: self as NSNumber)
return formattedDouble!
}
}
@Mreyna3
Mreyna3 / contents.swift
Last active June 6, 2019 05:41
computed property
fileprivate var batchSum : Double!{
willSet{
if (newValue > 0 && newValue > batchSum){
print("\((newValue - batchSum).format()) enqueud into the batch, the updated batch value is: \(newValue!.format())")
}
defaults.set(newValue, forKey: "batch_sum")
}
}
@Mreyna3
Mreyna3 / contents.swift
Created June 6, 2019 05:06
updated processBatch function
func processBatch(){
for _ in 0..<queue.getCount(){
batchSum -= queue.peek()!
//1
print("deueuing \(queue.dequeue()!.format())")
}
//2
print("deueuing \(batchSum!.format())")