diff --git a/10_fibonacci/fibonacci.js b/10_fibonacci/fibonacci.js index bb2c8cc..2279b0f 100644 --- a/10_fibonacci/fibonacci.js +++ b/10_fibonacci/fibonacci.js @@ -1,6 +1,19 @@ -const fibonacci = function() { +const fibonacci = function (index) { + if (index < 0) return 'OOPS' -}; + // in loop, add up the sequence until the length of the array is index - 1 + let seq = [1] + + while (seq.length < index) { + if (seq.length === 1) { + seq.push(1) + } else { + seq.push(seq.at(-1) + seq.at(-2)) + } + } + + return seq.pop() +} // Do not edit below this line -module.exports = fibonacci; +module.exports = fibonacci diff --git a/10_fibonacci/fibonacci.spec.js b/10_fibonacci/fibonacci.spec.js index 7f62213..49c341c 100644 --- a/10_fibonacci/fibonacci.spec.js +++ b/10_fibonacci/fibonacci.spec.js @@ -2,30 +2,30 @@ const fibonacci = require('./fibonacci') describe('fibonacci', () => { test('4th fibonacci number is 3', () => { - expect(fibonacci(4)).toBe(3); - }); - test.skip('6th fibonacci number is 8', () => { - expect(fibonacci(6)).toBe(8); - }); - test.skip('10th fibonacci number is 55', () => { - expect(fibonacci(10)).toBe(55); - }); - test.skip('15th fibonacci number is 610', () => { - expect(fibonacci(15)).toBe(610); - }); - test.skip('25th fibonacci number is 75025', () => { - expect(fibonacci(25)).toBe(75025); - }); - test.skip('doesn\'t accept negatives', () => { - expect(fibonacci(-25)).toBe("OOPS"); - }); - test.skip('DOES accept strings', () => { - expect(fibonacci("1")).toBe(1); - }); - test.skip('DOES accept strings', () => { - expect(fibonacci("2")).toBe(1); - }); - test.skip('DOES accept strings', () => { - expect(fibonacci("8")).toBe(21); - }); -}); + expect(fibonacci(4)).toBe(3) + }) + test('6th fibonacci number is 8', () => { + expect(fibonacci(6)).toBe(8) + }) + test('10th fibonacci number is 55', () => { + expect(fibonacci(10)).toBe(55) + }) + test('15th fibonacci number is 610', () => { + expect(fibonacci(15)).toBe(610) + }) + test('25th fibonacci number is 75025', () => { + expect(fibonacci(25)).toBe(75025) + }) + test('doesn\'t accept negatives', () => { + expect(fibonacci(-25)).toBe('OOPS') + }) + test('DOES accept strings', () => { + expect(fibonacci('1')).toBe(1) + }) + test('DOES accept strings', () => { + expect(fibonacci('2')).toBe(1) + }) + test('DOES accept strings', () => { + expect(fibonacci('8')).toBe(21) + }) +})