เราจำเป็นต้องเขียนฟังก์ชันโดยพูดว่า sumBetween() ที่รับอาร์เรย์ [a,b] ของสององค์ประกอบและส่งกลับผลรวมขององค์ประกอบทั้งหมดระหว่าง a และ b รวมถึง a และ b
ตัวอย่างเช่น −
[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