Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implements extra credit requirements #1

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 61 additions & 5 deletions calculator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ class CalculatorEngine

def initialize
@memory = []
@history = []
end


Expand All @@ -18,26 +19,45 @@ def run

if input
input = input.chomp
@history.push(input)

if input == 'q'
done = true
else
# operators will work on the stack, numbers will be added to stack
case input
when '0','1','2','3','4','5','6','7','8','9'
# ['0','1'].include?, %w(0 1).include?
@memory.push(input.to_f)
puts @memory.last
when 'c'
@memory = []
puts "Memory Cleared"
when 'ca'
@memory = []
@history = []
puts "Memory and History Cleared"
when 'm'
puts "Memory:"
position = 0
@memory.each do |m|
puts "\t#{position}: #{m}"
position = position + 1
end
when 'p'
puts "Paper Tape:"
position = 0
@history.each do |m|
puts "\t#{position}: #{m}"
position = position + 1
end
when 'pi'
@memory.push(3.14)
puts @memory.last
when 'sqrt'
if @memory.length >= 1
num = @memory.pop
@memory.push(Math.sqrt(num))
puts "= #{@memory.last}"
else
puts "Error: Not Enough Operands"
end
when '+'
if @memory.length >= 2
op1 = @memory.pop
Expand All @@ -47,8 +67,44 @@ def run
else
puts "Error: Not Enough Operands"
end
when '-'
if @memory.length >= 2
op1 = @memory.pop
op2 = @memory.pop
@memory.push(op1 - op2)
puts "= #{@memory.last}"
else
puts "Error: Not Enough Operands"
end
when '*'
if @memory.length >= 2
op1 = @memory.pop
op2 = @memory.pop
@memory.push(op1 * op2)
puts "= #{@memory.last}"
else
puts "Error: Not Enough Operands"
end
when '/'
if @memory.length >= 2
op1 = @memory.pop
op2 = @memory.pop
@memory.push(op1 / op2)
puts "= #{@memory.last}"
else
puts "Error: Not Enough Operands"
end
when '0','1','2','3','4','5','6','7','8','9'
# ['0','1'].include?, %w(0 1).include?
@memory.push(input.to_f)
puts @memory.last
else
puts "Error: Unsupported Operator: #{input}" unless input.empty?
if input =~ /^\d+\.\d*$/
@memory.push(input.to_f)
puts @memory.last
else
puts "Error: Unsupported Operator: #{input}" unless input.empty?
end
end

end
Expand Down