r/badcode • • Sep 10 '19

[deleted by user]

[removed]

16 Upvotes

22 comments sorted by

View all comments

1

u/Waspbot Sep 16 '19 edited Sep 16 '19

Javascript. Input 100,000,000 for a potential out-of-memory crash. Also, numbers less than 2 give incorrect output, but those aren't actual numbers in the sequence anyways, so just don't do it.

function findFibNum(n)
{
	class FibNum {
		constructor(parent) {this.lastNum = parent;}
		setNum(input) {
			switch (input) {
				case 0:
				case 1:
					this.val = input;
				break;
				default:
					this.val = this.lastNum.val + this.lastNum.lastNum.val;
				break;
			}
		}
	}

	num0 = new FibNum(new FibNum());
	num0.setNum(0);
	num1 = new FibNum(num0);
	num1.setNum(1);
	arr = [num0,num1];
	for (let i = 2; i <n; i++) {
		arr.push(new FibNum(arr[i-1]));
		arr[i].setNum();
	}

	currentFibNum = arr[arr.length-1];
	output = "";
	while (currentFibNum.lastNum) {
		output = currentFibNum.val + ", " + output;
		currentFibNum = currentFibNum.lastNum;
	}
	return output.slice(0, output.length-2);
}