Skip to content

Instantly share code, notes, and snippets.

@mattisa
Last active March 20, 2017 12:22
Show Gist options
  • Save mattisa/6302487fa99c919a9eab23e0d21ec025 to your computer and use it in GitHub Desktop.
Save mattisa/6302487fa99c919a9eab23e0d21ec025 to your computer and use it in GitHub Desktop.
Simple calculator with function chaining
const plus = (a, b) => a + b;
const minus = (a, b) => a - b;
const multiply = (a, b) => a * b;
const divide = (a, b) => a / b;
const Calc = (a) => ({
plus: (...b) => Calc(b.reduce(plus, a)),
minus: (...b) => Calc(b.reduce(minus, a)),
multiply: (...b) => Calc(b.reduce(multiply, a)),
divide: (...b) => Calc(b.reduce(divide, a)),
value: () => a
});
module.exports = Calc
const Calc = require('./index');
let calc;
describe('calculator', () => {
beforeEach(() => {
calc = Calc(10);
});
it('plus', () => {
expect(calc.plus(3).value()).toBe(13);
});
it('minus', () => {
expect(calc.minus(2).value()).toBe(8);
});
it('multiply once', () => {
expect(calc.multiply(2).value()).toBe(20);
});
it('multiply several', () => {
expect(calc.multiply(2, 5).value()).toBe(100);
});
it('divide', () => {
expect(calc.divide(2).value()).toBe(5);
});
it('divide several', () => {
expect(calc.divide(2, 2).value()).toBe(2.5);
});
it('combination', () => {
expect(calc.plus(2).multiply(2, 4).divide(3).value()).toBe(32);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment