From bea72d0a8a62998de1c375f76ac4db0120b3da0a Mon Sep 17 00:00:00 2001 From: zhabinka Date: Mon, 21 Jan 2019 20:11:06 +0300 Subject: [PATCH] Added Collatz Conjecture --- .../collatz-conjecture/collatz-conjecture.js | 22 +++++++++++++ .../collatz-conjecture.spec.js | 31 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 javascript/collatz-conjecture/collatz-conjecture.js create mode 100644 javascript/collatz-conjecture/collatz-conjecture.spec.js diff --git a/javascript/collatz-conjecture/collatz-conjecture.js b/javascript/collatz-conjecture/collatz-conjecture.js new file mode 100644 index 0000000..7c25960 --- /dev/null +++ b/javascript/collatz-conjecture/collatz-conjecture.js @@ -0,0 +1,22 @@ +// If n is even, divide n by 2 to get n / 2. +// If n is odd, multiply n by 3 and add 1 to get 3n + 1. + +const operation = n => (n % 2 === 0 ? n / 2 : 3 * n + 1); + +const steps = (number) => { + if (number <= 0) { + throw new Error('Only positive numbers are allowed'); + } + + const iter = (num, count) => { + if (num === 1) { + return count; + } + + return iter(operation(num), count + 1); + }; + + return iter(number, 0); +}; + +export { steps }; diff --git a/javascript/collatz-conjecture/collatz-conjecture.spec.js b/javascript/collatz-conjecture/collatz-conjecture.spec.js new file mode 100644 index 0000000..53c45ba --- /dev/null +++ b/javascript/collatz-conjecture/collatz-conjecture.spec.js @@ -0,0 +1,31 @@ +import { steps } from './collatz-conjecture'; + +describe('steps()', () => { + test('zero steps for one', () => { + expect(steps(1)).toEqual(0); + }); + + test('divide if even', () => { + expect(steps(16)).toEqual(4); + }); + + test('even and odd steps', () => { + expect(steps(12)).toEqual(9); + }); + + test('Large number of even and odd steps', () => { + expect(steps(1000000)).toEqual(152); + }); + + test('zero is an error', () => { + expect(() => { + steps(0); + }).toThrow(new Error('Only positive numbers are allowed')); + }); + + test('negative value is an error', () => { + expect(() => { + steps(-15); + }).toThrow(new Error('Only positive numbers are allowed')); + }); +});