Skip to content

Instantly share code, notes, and snippets.

@manix84
Last active February 8, 2017 15:08
Show Gist options
  • Select an option

  • Save manix84/5663766 to your computer and use it in GitHub Desktop.

Select an option

Save manix84/5663766 to your computer and use it in GitHub Desktop.
This is my reference when phone screening.
var fibonacci = function (position) {
return position < 1 ? 0 :
position <= 2 ? 1 :
fibonacci(position - 1) + fibonacci(position - 2);
};
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;
};
(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