|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Calculator |
| 4 | + # Refactored calculator implementation. Uses a function lookup to determine |
| 5 | + # which operation to perform. |
| 6 | + class Refactored |
| 7 | + def initialize(value = 0) |
| 8 | + @value = value |
| 9 | + end |
| 10 | + |
| 11 | + OPERATIONS = { |
| 12 | + "add" => :add, |
| 13 | + "subtract" => :subtract, |
| 14 | + "multiply" => :multiply, |
| 15 | + "divide" => :divide |
| 16 | + }.freeze |
| 17 | + |
| 18 | + def execute(command) |
| 19 | + values = command.split(" ") |
| 20 | + operation = values[0] |
| 21 | + first_operand = values[1].to_f |
| 22 | + second_operand = values.length > 2 ? values[2].to_f : nil |
| 23 | + |
| 24 | + raise "Invalid operation" unless OPERATIONS.key?(operation) |
| 25 | + |
| 26 | + send(OPERATIONS[operation], first_operand, second_operand) |
| 27 | + end |
| 28 | + |
| 29 | + def add(first_operand, second_operand) |
| 30 | + if !second_operand.nil? |
| 31 | + @value = first_operand + second_operand |
| 32 | + else |
| 33 | + @value += first_operand |
| 34 | + end |
| 35 | + end |
| 36 | + |
| 37 | + def subtract(first_operand, second_operand) |
| 38 | + if !second_operand.nil? |
| 39 | + @value = first_operand - second_operand |
| 40 | + else |
| 41 | + @value -= first_operand |
| 42 | + end |
| 43 | + end |
| 44 | + |
| 45 | + def multiply(first_operand, second_operand) |
| 46 | + if !second_operand.nil? |
| 47 | + @value = first_operand * second_operand |
| 48 | + else |
| 49 | + @value *= first_operand |
| 50 | + end |
| 51 | + end |
| 52 | + |
| 53 | + def divide(first_operand, second_operand) |
| 54 | + if !second_operand.nil? |
| 55 | + @value = first_operand / second_operand |
| 56 | + else |
| 57 | + @value /= first_operand |
| 58 | + end |
| 59 | + end |
| 60 | + |
| 61 | + def result |
| 62 | + @value |
| 63 | + end |
| 64 | + end |
| 65 | +end |
0 commit comments