-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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')); | ||
}); | ||
}); |