เมื่อเว็บและแอปพลิเคชันซับซ้อนขึ้น JavaScript และ Node.js กำลังกลายเป็นข้อกำหนดทั่วไปใน repertoire ของนักพัฒนา เพื่อปรับปรุง code-foo และลดปวดหัวที่เจอ คุณสามารถ define functions บางอย่างตั้งแต่ต้นโค้ด ที่ทำ simple tasks ให้เสร็จเร็ว
โปรดทราบ: JavaScript ไม่เหมือน Java ดูความแตกต่างที่นี่
1. สลับค่าใน Array
เหมือนการสลับไพ่ คุณสามารถสลับค่าใน array บ่อยแค่ไหนก็ได้ใน JavaScript ด้วย one-liner นี้:
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
ต่อยอดกับ analogy ไพ่ โค้ดจะเป็นแบบนี้ถ้าอยากสลับ 52 ค่า:
let myarray = Array.from({length:52}, (v,k) => k+1); console.log(shuffleArray(myarray));
โค้ดควรแสดงค่าที่สลับสุ่มใน console output
2. ตรวจสอบว่า Date ตรง Weekend หรือ Weekday
ใช้ remainder operand เรียบง่าย สามารถเช็คได้ง่ายว่าวันตรง weekend ใน JavaScript:
const isWeekend = (date) => date.getDay() % 6 == 0;
หากอยากเปลี่ยนเช็คว่า weekday แค่ reverse การเปรียบเทียบสุดท้าย:
const isWeekday = (date) => date.getDay() % 6 !== 0;
โค้ดต่อไป เช็คว่า اليوم weekend หรือไม่:
console.log(isWeekend(new Date()));
ทางเลือกแทนการ define isWeekday หรือ isWeekend แยก ใช้ NOT operand ใน if-then-else statement สำหรับตัวไหนตัวหนึ่ง:
if (!isWeekend(new Date())) { console.log("Today falls on a weekday."); } else { console.log("Today falls on a weekend."); }
3. ตัดตัวเลขให้เหลือ decimal places ที่ต้องการ
Output ให้ผู้ใช้ต้อง simple ที่สุด ไม่มีอะไรทำให้ site/app unappealing กว่าการเห็น string ตัวเลขยาวๆ เพื่อตัด decimal places ที่ less significant แสดงให้ user เรียบร้อย ใช้ definition นี้:
const decimalFormat = (n, places) => ~~(Math.pow(10, places) * n) / Math.pow(10, places);
ทดสอบ: define ค่าตัวเลขกับ decimal places มากเกินไป เรียก quick function ตัดเหลือ 2 decimal places
let deciwow = 299.39542014592 console.log(decimalFormat(deciwow, 2));
ผลลัพธ์ควรดูน่าสบายตากว่าเดิม
4. แปลงอุณหภูมิ
ใน JavaScript ไม่มี standardized way แปลง Celsius กับ Fahrenheit แต่ด้วย 2 one-liners สร้าง standard เองได้
Celsius ถึง Fahrenheit:
const cToF = (celsius) => celsius * 9/5 + 32;
Fahrenheit ถึง Celsius:
const fToC = (fahrenheit) => (fahrenheit - 32) * 5/9;
ในเมืองผม อุณหภูมิ -2°C ใช้ one-liner Celsius to Fahrenheit หาความหมายให้คนใน US:
cToF(-2);
Expression นี้ให้อุณหภูมิ 28.4°F
5. เช็คว่าใครใช้ Dark Mode
หากต้องการ content ที่แสดง respect color scheme ของผู้ใช้ JavaScript มีวิธี detect dark mode เพื่อปรับสีตามนั้น Method ค่อนข้างซับซ้อน แต่ shorten ได้ด้วย one-liner นี้:
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
ตัวอย่างเช็คด้วย variable นี้:
if (isDarkMode) { console.log("This screen is in dark mode."); } else { console.log("This screen is not using dark mode."); }
หมายเหตุ: โค้ดนี้ทำงานใน JavaScript สำหรับ browsers เท่านั้น Node.js ไม่ implement support สำหรับ window
6. หาค่าเฉลี่ยของ Array ตัวเลข
จัดการ datasets JavaScript มี handy function ผูกกับ arrays ให้ arithmetic รวมค่าทั้งหมดใน table แล้วหารด้วยความยาวของ table เพื่อทำให้ขlegant ใน one line of code:
const getAverage = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
สร้าง dataset และ pump average ทั้งหมดออก console:
let dataset = [2, 14, 88, 204, 1515, 1294, 12, 144]; console.log(getAverage(dataset));
โค้ดนี้ output ควรเป็น 409.125
7. สร้าง UUID
หากอยากเก็บสถิติและข้อมูลจากผู้ใช้แอป (เช่น generate cookie) วิธีดีที่สุดโดยไม่ invasive คือ generate universally unique identifier (UUID) JavaScript ไม่มี easy way generate RFC4122-compliant UUIDs (แม้ Node.js มี uuid npm package ให้ functionality นี้ out of the box)
ใน JS สร้าง UUID ใหม่สำเร็จรูปให้ผู้ใช้ด้วย one-line expression:
const genUUID = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, genUUID));
ทดสอบ output:
console.log(genUUID());
8. หาจำนวนวันระหว่าง 2 วันที่
เวลากำหนดอายุของค่าเฉพาะ (เช่น account ของ user) ต้องคำนวณวันที่ผ่านมาตั้งแต่จุดหนึ่ง one-liner เรียบง่ายทำได้:
const ageDays = (old, recent) => Math.ceil(Math.abs(old - recent) / (1000 * 60 * 60 * 24));
ตัวอย่าง use case: สมมติ assess อายุ user สร้าง account วันที่ 28 ธันวาคม 2012 ใช้ declaration นี้หาจำนวนวันระหว่างวันนั้นกับวันนี้:
console.log(ageDays(new Date('2012-12-28'), new Date()));
ขณะเขียน ควรได้ผล 3298 วัน
9. สร้างสุ่มตัวเลขในช่วงที่กำหนด
บางครั้ง generate random number แค่ตัวเดียวไม่พอ อาจต้อง limit conditions ที่ generate ด้วย one-liner นี้ generate numbers ในช่วงที่ระบุ:
const rangeRandom = (low, high) => Math.floor(Math.random() * (high - low + 1)) + low;
ทดสอบง่าย:
console.log(rangeRandom(400, 20000));
คำถามที่พบบ่อย
1. ทำไมใช้ UUIDs ใน cookies?
Cookies โดยธรรมชาติ intrusive และใช้พื้นที่บนเครื่อง user ควรมีประสิทธิภาพและ non-invasive ที่สุดเมื่อใช้เครื่องมือเหล่านี้เก็บข้อมูล UUID ให้ประโยชน์ 2 ด้าน: แรก minimize พื้นที่ client-based storage เพราะ identifier แค่ 128 bits 二、ไม่ depend บน personal data ของ user
2. ได้ error "window is not defined" ใน Node.js ตอน detect dark mode ทำไง?
Node.js ไม่สามารถ call client-side modules ได้ เพราะไม่มี intrinsic client-server relationship เหมือน JavaScript Dark mode detection one-liner ในบทความนี้ meant สำหรับ browser-based JavaScript เท่านั้น
3. โค้ดนี้ universal ทุก browser ไหม?
JavaScript code ใช้ interpreter ควร function universally ทฤษฎีทำงานทุก browser แต่วิธี interpret โค้ดอาจต่างเล็กน้อย โดยเฉพาะ software เก่าๆ สำหรับ one-liners ที่แสดงที่นี่ ควร return ผลลัพธ์เดียวกัน ไม่ว่า browser ไหน แต่ระวัง: features บางอย่างใน JavaScript โดยทั่วไปอาจไม่ทำงานบน browsers เช่น Pale Moon, Internet Explorer, หรือ early-2000s versions ของ browsers ที่พัฒนาอยู่