Last active
February 8, 2017 15:08
-
-
Save manix84/5663766 to your computer and use it in GitHub Desktop.
This is my reference when phone screening.
This file contains hidden or 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
| var fibonacci = function (position) { | |
| return position < 1 ? 0 : | |
| position <= 2 ? 1 : | |
| fibonacci(position - 1) + fibonacci(position - 2); | |
| }; |
This file contains hidden or 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
| var fibonacci = function (position) { | |
| var previous = 0, | |
| tmpCurrent, | |
| current = (position > 0 ? 1 : 0); | |
| for (var i = 1; i < position; ++i) { | |
| tmpCurrent = current; | |
| current += previous; | |
| previous = tmpCurrent; | |
| } | |
| return current; | |
| }; |
This file contains hidden or 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
| (function fibonacciTest() { | |
| var tests = [0, 0, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], // This array will be shifted from 0 to -2. | |
| len = tests.length, | |
| i = 0, | |
| answerA, answerB, prefixMessage; | |
| for (; i < len; ++i) { | |
| answerA = fibonacci(i - 2); | |
| answerB = tests[i]; | |
| prefixMessage = ("fibonacci(" + (i - 2) + ") = " + answerA); | |
| if (answerA === answerB) { | |
| console.log(prefixMessage, "✓"); | |
| } else { | |
| console.error(prefixMessage, "✗ - It should be: " + answerB); | |
| return false; | |
| } | |
| } | |
| return true; | |
| }()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment