Resistance calculator: Difference between revisions
Content added Content deleted
No edit summary |
No edit summary |
||
Line 136: | Line 136: | ||
print(" Ohm Volt Ampere Watt Network tree") |
print(" Ohm Volt Ampere Watt Network tree") |
||
node.report() |
node.report() |
||
</lang> |
|||
=={{header|CoffeeScript}}== |
|||
<lang coffeescript> |
|||
nd = (num) -> num.toFixed(3).padStart 8 |
|||
class Resistor |
|||
constructor : (@resistance,@a=null,@b=null,@symbol='r') -> |
|||
res : -> @resistance |
|||
setVoltage : (@voltage) -> |
|||
current : -> @voltage / @res() |
|||
effect : -> @current() * @voltage |
|||
report : (level) -> |
|||
print "#{nd @res()} #{nd @voltage} #{nd @current()} #{nd @effect()} #{level}#{@symbol}" |
|||
if @a then @a.report level + "| " |
|||
if @b then @b.report level + "| " |
|||
class Serial extends Resistor |
|||
constructor : (a,b) -> super 0,a,b,'+' |
|||
res : -> @a.res() + @b.res() |
|||
setVoltage : (@voltage) -> |
|||
ra = @a.res() |
|||
rb = @b.res() |
|||
@a.setVoltage ra/(ra+rb) * @voltage |
|||
@b.setVoltage rb/(ra+rb) * @voltage |
|||
class Parallel extends Resistor |
|||
constructor : (a,b) -> super 0,a,b,'*' |
|||
res : -> 1 / (1 / @a.res() + 1 / @b.res()) |
|||
setVoltage : (@voltage) -> |
|||
@a.setVoltage @voltage |
|||
@b.setVoltage @voltage |
|||
build = (voltage, s) -> |
|||
stack = [] |
|||
for word in s.split ' ' |
|||
if word == '+' then stack.push new Serial stack.pop(), stack.pop() |
|||
else if word == '*' then stack.push new Parallel stack.pop(), stack.pop() |
|||
else stack.push new Resistor parseFloat word |
|||
node = stack.pop() |
|||
node.setVoltage voltage |
|||
node |
|||
node = build 18.0, "10 2 + 6 * 8 + 6 * 4 + 8 * 4 + 8 * 6 +" |
|||
print " Ohm Volt Ampere Watt Network tree" |
|||
node.report "" |
|||
</lang> |
</lang> |