Skip to content

Instantly share code, notes, and snippets.

@ecasilla
Created September 22, 2015 03:38
Show Gist options
  • Save ecasilla/c3c4e95bc8699e12ac80 to your computer and use it in GitHub Desktop.
Save ecasilla/c3c4e95bc8699e12ac80 to your computer and use it in GitHub Desktop.
Awesome Calculator
function Calculator() {}
function reduceArgs(operation) {
return function() {
var args = Array.prototype.slice.call(arguments);
var ops = {
'+': function(x, y) {
return x + y;
},
'-': function(x, y) {
return x - y;
},
'/': function(x, y) {
return x / y;
},
'*': function(x, y) {
return x * y;
}
};
var result = args.reduce(function(prev, curr) {
return ops[operation](prev, curr);
}, 0);
return result;
};
}
Calculator.prototype.add = reduceArgs('+');
Calculator.prototype.subtract = reduceArgs('-');
Calculator.prototype.multiply = reduceArgs('*');
Calculator.prototype.divide = reduceArgs('/');
module.exports = Calculator;
var Calculator = require('../../app/scripts/calculator.js');
var expect = require('chai').expect;
var context = describe;
//MOCHA + CHAI
describe('Calculator App: ', function(){
var calc;
context('Interface: ', function(){
before(function(){
calc = new Calculator();
});
it('Should exist', function(){
expect(Calculator).to.be.an('function');
});
it('Should be a constructor function', function(){
expect(calc).to.be.an.instanceof(Calculator);
});
it('should have a add method', function(){
expect(calc).to.respondTo('add');
});
it('should have a subtract method', function(){
expect(calc).to.respondTo('subtract');
});
it('should have a multiply method', function(){
expect(calc).to.respondTo('multiply');
});
it('should have a divide method', function(){
expect(calc).to.respondTo('divide');
});
});
context("Implementation of Calculator: ",function() {
before(function(){
calc = new Calculator();
});
it('should add two numbers', function(){
expect(calc.add(1,3)).to.equal(4);
});
it('should also sum an array of numbers ',function() {
expect(calc.add(1,2,3,4,5)).to.equal(15);
});
});
});
@duythiensl
Copy link

duythiensl commented Jul 1, 2017

ops[operation](prev, curr);

and

var ops = {
            '+': function(x, y) {
                return x + y;
            },
            '-': function(x, y) {
                return x - y;
            },
            '/': function(x, y) {
                return x / y;
            },
            '*': function(x, y) {
                return x * y;
            }
        };

Can you explain the structure of the code above help me?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment