Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fanaugen/1dd49ce9a556b435c01956762d2a99d0 to your computer and use it in GitHub Desktop.
Save fanaugen/1dd49ce9a556b435c01956762d2a99d0 to your computer and use it in GitHub Desktop.
GoCardless Coding Challenge 1: Fraud Detection Shortest Code Challenge

Scenario

You're developing a system to analyze transactions for potential fraud.

You have a list of transactions, each with a variety of attributes like amount, currency, status, and a fraud score.

Your goal is to calculate total amounts for different currencies only for transactions flagged non clean.

You shall refactor ONLY the analyze_transactions method to be the shortest possible, without changing any other pieces of the code.

transactions = [
{ id: 1, amount: 100, currency: 'USD', status: 'potential_fraud', fraud_score: 85 },
{ id: 2, amount: 200, currency: 'EUR', status: 'potential_fraud', fraud_score: 90 },
{ id: 3, amount: 150, currency: 'USD', status: 'clean', fraud_score: 10 },
{ id: 4, amount: 300, currency: 'USD', status: 'potential_fraud', fraud_score: 88 },
{ id: 5, amount: 250, currency: 'EUR', status: 'clean', fraud_score: 5 },
{ id: 6, amount: 400, currency: 'GBP', status: 'potential_fraud', fraud_score: 92 },
{ id: 7, amount: 50, currency: 'GBP', status: 'potential_fraud', fraud_score: 80 }
]
class Task
def initialize(transactions)
@transactions = transactions
end
def analyze_transactions
def total_usd_fraud
total_usd = 0
@transactions.each do |tx|
if tx[:currency] == 'USD' && tx[:status] == 'potential_fraud'
total_usd += tx[:amount]
end
end
total_usd
end
def total_eur_fraud
total_eur = 0
@transactions.each do |tx|
if tx[:currency] == 'EUR' && tx[:status] == 'potential_fraud'
total_eur += tx[:amount]
end
end
total_eur
end
def total_gbp_fraud
total_gbp = 0
@transactions.each do |tx|
if tx[:currency] == 'GBP' && tx[:status] == 'potential_fraud'
total_gbp += tx[:amount]
end
end
total_gbp
end
end
def run
analyze_transactions
puts total_usd_fraud, total_eur_fraud, total_gbp_fraud
end
end
class Solution
def initialize(transactions) = @transactions = transactions
def analyze_transactions
def method_missing(m,*a)[email protected](&:values).map{_1[2]=~/^#{m[6]}/i&&_1[3]=~/f/?_1[1]:0}.sum
end
def run
analyze_transactions
puts total_usd_fraud, total_eur_fraud, total_gbp_fraud
end
end
Task.new(transactions).run
Solution.new(transactions).run
@fanaugen
Copy link
Author

This final version is the shortest I can make, but quite unreadable.

The previous version was a little longer and more readable, because it had whitespace and used .compact instead of a ternary operator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment