JavaScript!!!

💻 문제 (~21:15)

피보나치 수는 F(0) = 0, F(1) = 1일 때, 2 이상의 n에 대하여 F(n) = F(n-1) + F(n-2) 가 적용되는 점화식입니다. 2 이상의 n이 입력되었을 때, fibonacci 함수를 제작하여 n번째 피보나치 수를 반환해 주세요. 예를 들어 n = 3이라면 2를 반환해주면 됩니다.

ex_ F(4)인 경우 0 1 1 2 '3' 이므로 F(4) = 3 입니다.
function arraySum(acc, current) {
	return acc + current;
}

function isNonNagativeInteger(n) {
  const isInteger = n === Math.floor(n);
	const nan = Number.isNaN(n);
	const isNagative = n < 0;
	const isValid = isInteger && !nan && !isNagative;
	
	return isValid;
}

function F(n = 0) {
	if(typeof n !== 'number') throw new Error('N must be Number type');
	if(!isNonNagativeInteger(n)) throw new Error('N must be non nagative integer');	

	let prevNumbers = [0, 1];
	let result = prevNumbers[n];

	for(let currentIndex = 2; currentIndex <= n; currentIndex++) {
		result = prevNumbers.reduce(arraySum, 0);
		prevNumbers = [
			...prevNumbers.slice(1),
			result
		];
	}

  return result;
}

💻 문제2 (~21:40)

waterMelon함수는 정수 n을 매개변수로 입력받습니다.

길이가 n이고, 수박수박수…와 같은 패턴을 유지하는 문자열을 리턴하도록 함수를 완성하세요.

ex_ waterMelon(4)이 4이면 ‘수박수박’을 리턴하고 waterMelon(3)이라면 ‘수박수’를 리턴하면 됩니다.
function isNonNagativeInteger(n) {
  const isInteger = n === Math.floor(n);
	const nan = Number.isNaN(n);
	const isNagative = n < 0;
	const isValid = isInteger && !nan && !isNagative;
	
	return isValid;
}

function waterMelon(n){
	if(typeof n !== 'number') throw new Error('N must be Number type');
	if(!isNonNagativeInteger(n)) 
		throw new Error('N must be non nagative integer');	

	const arr = ["수", "박"]
	let result = "";

	for (let index = 0; index < n; index++) {
		result += arr[index % 2];
	}
	
	return result;
}

function, () ⇒ {}