หมายเลขเส้นทางชีวิต
หมายเลขเส้นทางชีวิตของแต่ละคนคำนวณโดยการเพิ่มแต่ละหมายเลขในวันเกิดของบุคคลนั้นจนกว่าจะลดลงเป็นตัวเลขหลักเดียว
ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้วันที่ในรูปแบบ “yyyy-mm-dd” และส่งกลับหมายเลขเส้นทางชีวิตของวันเกิดนั้น
ตัวอย่างเช่น
หากเป็นวันที่:1999-06-10
year : 1 + 9 + 9 + 9 = 28 → 2 + 8 = 10 → 1 + 0 = 1 month : 0 + 6 = 6 day : 1 + 0 = 1 result: 1 + 6 + 1 = 8
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const date = '1999-06-10';
const findLifePath = (date = '') => {
const sum = (arr = []) => {
if(arr.length === 1){
return +arr[0]
};
let total = arr.reduce((acc, val) => acc + val);
if (total < 10){
return total
};
return sum(String(total).split("").map(Number));
};
let [year, month, day] = date.split("-")
year = sum(String(year).split("").map(Number));
month = sum(String(month).split("").map(Number));
day = sum(String(day).split("").map(Number));
return sum([year,month,day]);
};
console.log(findLifePath(date)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
8