The RPN calculator implementation is a good exercise for working through a languages capabilities and exploring OO strategies.
I have done four variations of the RPN calculator as exploratory into languages:
This implementation utilizes node.js and mocha.
To install node.js, either download or install using brew
brew install nodeTo install the node modules:
npm installYou can run the calculator from the command line by running:
node calculator-commandline.js 1 2 +Note that '*' has unix command line meaning, so us 'x' or '\*' for multiplication.
>node calculator-commandline.js 3 2 \*
result: 6
>node calculator-commandline.js 3 2 x
result: 6To run the unit tests, run the following shell script:
npm test-
Create a new operator implementation class. Add this class to the
operatorsdirectory. Follow the conventation of(operator name)-operator.js(example:addition-operator.js). -
The operator implementation class needs to implement a function
function(numbers), where numbers is an instance of RPN-stack. The function is responsible forpop-ing the operands necessary to perform the operation, andpush-ing the result back to the stack. Either export this asmodule.exports.doOperationormodule.exports
A sample base implementation for addition is shown below:
module.exports = function(numbers) {
var rhs = numbers.pop();
var lhs = numbers.pop();
var result = lhs + rhs;
numbers.push(result);
return result;
};- Register operator in
operator-register.js. To do this, add the following statement:
registry.registerHandler("+", require("./operators/addition-operator"));