Last active
February 26, 2022 10:48
-
-
Save tejo/eb95a053ca525d226b68d18cff70c328 to your computer and use it in GitHub Desktop.
cleo coding challenge
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
# frozen_string_literal: true | |
class ChangeCalculator | |
COINS = { 200 => '£2', 100 => '£1', 50 => '50p', 20 => '20p', 10 => '10p', 5 => '5p', 2 => '2p', 1 => '1p' }.freeze | |
def self.calculate(amount) | |
new(amount).calculate | |
end | |
def initialize(amount) | |
@amount = (amount * 100).to_i | |
@change = {} | |
end | |
def calculate | |
COINS.keys.each do |coin| | |
result = @amount / coin | |
if result >= 1 | |
@change[COINS[coin]] = result.to_int | |
@amount -= (result.to_int * coin) | |
end | |
end | |
@change | |
end | |
end |
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
# frozen_string_literal: true | |
require 'change_calculator' | |
RSpec.describe ChangeCalculator do | |
context 'change calculator' do | |
it 'returns right change for 2.12' do | |
expect(ChangeCalculator.calculate(2.12)).to eq({ '£2' => 1, '10p' => 1, '2p' => 1 }) | |
end | |
it 'returns right change for 2.00' do | |
expect(ChangeCalculator.calculate(2.00)).to eq({ '£2' => 1 }) | |
end | |
it 'returns right change for 4.00' do | |
expect(ChangeCalculator.calculate(4.00)).to eq({ '£2' => 2 }) | |
end | |
it 'returns right change for 3.26' do | |
expect(ChangeCalculator.calculate(3.26)).to eq({ '1p' => 1, '20p' => 1, '5p' => 1, '£1' => 1, '£2' => 1 }) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment