Skip to content

Instantly share code, notes, and snippets.

@calvinf
Created June 24, 2017 15:46
Show Gist options
  • Save calvinf/fb41c052e5a2d955738f19298080aaa7 to your computer and use it in GitHub Desktop.
Save calvinf/fb41c052e5a2d955738f19298080aaa7 to your computer and use it in GitHub Desktop.
Curried Multiply
<!doctype html>
<html>
<head>
<title>Multiply</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.4.2/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.0.2/chai.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.4.2/mocha.min.js"></script>
<script>
// curried multipier that calls itself
// until it has no more arguments passed in
// and when its done returns the product of all multiples
const multiply = function (...args) {
// we keep adding multiples into this list
let multiples = [];
// we return this function to handle accumulating multiples
const fn = function (...more) {
// if there aren't anymore args, we finally
// return the multiplied result of all the arguments
// across all the calls
if (!more.length) {
if (!multiples.length) {
throw new Error('no multiples provided');
}
return multiples.reduce((acc, curr) => acc * curr);
}
// if there are still more numbers, add to multiples
multiples.push(...more);
// return back this function so we can call it again
// and keep going
return fn;
}
// first time multiply is called, we call fn with
// the initial arguments passed in to get started
return fn(...args);
}
// test runner
const { expect } = window.chai;
mocha.setup('bdd');
// tests
describe('it multiplies correctly', () => {
it('handles being called once', () => {
expect(multiply(4, 5)()).to.equal(20);
});
it('handles being called twice', () => {
expect(multiply(4, 5)(2, 3)()).to.equal(120);
});
it('handles being called thrice', () => {
expect(multiply(4, 5)(2, 3)(3)()).to.equal(360);
});
it('handles three or more arguments', () => {
expect(multiply(7, 8, 9)(10)()).to.equal(5040);
})
});
// run tests
mocha.run();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment