우리는 두 개의 요소로 구성된 배열 [a,b]를 가져와서 b와 b를 포함한 모든 요소의 합을 반환하는 sumBetween()과 같은 함수를 작성해야 합니다.
예를 들어 -
[4, 7] = 4+5+6+7 = 22 [10, 6] = 10+9+8+7+6 = 40
이 함수의 코드를 작성해 봅시다 -
예시
const arr = [10, 60];
const sumUpto = (n) => (n*(n+1))/2;
const sumBetween = (array) => {
if(array.length !== 2){
return -1;
}
const [a, b] = array;
return sumUpto(Math.max(a, b)) - sumUpto(Math.min(a, b)) + Math.min(a,b);
};
console.log(sumBetween(arr));
console.log(sumBetween([4, 9])); 출력
콘솔의 출력은 다음과 같습니다. -
1785 39