Created
December 20, 2022 23:25
-
-
Save leandronsp/a6b4f03d831b0ebe7eb89fa332094bc2 to your computer and use it in GitHub Desktop.
Purchases Checker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit' | |
require 'digest' | |
require 'date' | |
class PurchasesChecker | |
attr_reader :authorizations | |
def initialize | |
@authorizations = [] | |
@purchases_idx = {} | |
end | |
def authorize!(customer, store, requested_at, amount) | |
body = "#{customer} #{store}" | |
md5 = Digest::MD5.hexdigest(body) | |
timestamp = requested_at.to_time.to_i | |
return if duplicate?(md5, timestamp) | |
@authorizations.append({ | |
customer: customer, | |
store: store, | |
requested_at: requested_at.to_time, | |
amount: amount | |
}) | |
@purchases_idx[md5] = timestamp | |
end | |
def duplicate?(md5, timestamp) | |
return false unless @purchases_idx[md5] | |
timestamp - @purchases_idx[md5] < 900 | |
end | |
end | |
class AuthorizationsTest < Test::Unit::TestCase | |
def test_idempotence | |
checker = PurchasesChecker.new | |
checker.authorize!('leandro', 'cafe sao paulo', DateTime.new(2022, 12, 20, 06, 00), 8) | |
checker.authorize!('john', 'cafe sao paulo', DateTime.new(2022, 12, 20, 06, 00), 12) | |
checker.authorize!('leandro', 'mesbla', DateTime.new(2022, 12, 20, 06, 05), 120) | |
checker.authorize!('leandro', 'cafe sao paulo', DateTime.new(2022, 12, 20, 06, 31), 10) | |
checker.authorize!('mary', 'mesbla', DateTime.new(2022, 12, 20, 10, 30), 100) | |
checker.authorize!('mary', 'mesbla', DateTime.new(2022, 12, 20, 10, 32), 150) | |
checker.authorize!('mary', 'mesbla', DateTime.new(2022, 12, 20, 10, 52), 100) | |
expected = [ | |
{ customer: 'leandro', store: 'cafe sao paulo', requested_at: DateTime.new(2022, 12, 20, 06, 00).to_time, amount: 8 }, | |
{ customer: 'john', store: 'cafe sao paulo', requested_at: DateTime.new(2022, 12, 20, 06, 00).to_time, amount: 12 }, | |
{ customer: 'leandro', store: 'mesbla', requested_at: DateTime.new(2022, 12, 20, 06, 05).to_time, amount: 120 }, | |
{ customer: 'leandro', store: 'cafe sao paulo', requested_at: DateTime.new(2022, 12, 20, 06, 31).to_time, amount: 10 }, | |
{ customer: 'mary', store: 'mesbla', requested_at: DateTime.new(2022, 12, 20, 10, 30).to_time, amount: 100 }, | |
{ customer: 'mary', store: 'mesbla', requested_at: DateTime.new(2022, 12, 20, 10, 52).to_time, amount: 100 } | |
] | |
assert_equal expected, checker.authorizations | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment