รวม javascript utils ฟังก์ชั่นอรรถประโยชน์ที่ใช้งานบ่อย
รวม javascript utils ฟังก์ชั่นอรรถประโยชน์ที่ใช้งานบ่อย
ฟังก์ชั่น Utils สำหรับการเขียนโปรแกรมคือการรวบรวมฟังก์ชั่นอรรถประโยชน์ที่ใช้งานบ่อย ๆ มาสร้างเป็นคลาสชื่อว่า utils และนำไปใช้งานในคลาสอื่นหรือส่วนต่าง ๆ ในขั้นตอนของการพัฒนา สำหรับภาษา javascript เราสามารถสร้างไฟล์ utils.js เพื่อเก็บรวบรวมฟังก์ชั่นอรรถประโยชน์ต่าง ๆ ไว้ใช้งานได้เช่นกัน ตัวอย่างฟังก์ชั่นต่าง ๆ ที่เรามักจะใช้งานอยู่บ่อย ๆ ในการเขียนภาษา javascript
ฟังก์ชั่นการคำนวณเปอร์เซ็นต์ใน javascript
function calPercentag(percent,amount){
var discount = (percent*amount)/100;
return discount;
}
ตัวอย่างการใช้งาน เมื่อเราต้องการรู้ว่า 10% ของ 120 คือเท่าไหร่
calPercentag(10,120); //ผลลัพธ์ = 12
ฟังก์ชั่นเพิ่มเครื่องหมาย comma สำหรับตัวเลข
function addComma(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
ตัวอย่างการใช้งาน ตัวฟังก์ชั่นจะเปลี่ยนพารามิเตอร์ number ที่ส่งเข้ามาในฟังก์ชั่นออกไปเป็น string ที่มีเครื่องหมาย comma
addComma(1400); //ผลลัพธ์ = 1,400
ฟังก์ชั่นสุ่มโค๊ดสีแบบ hex
function randomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}ตัวอย่างการใช้งาน
randomColor(); // ผลลัพธ์ = #650DE6
ฟังก์ชั่นสุ่มโค๊ดรหัส
function randomCode() {
var code = "";
var possible = "abcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 10; i++ )
code += possible.charAt(Math.floor(Math.random() * possible.length));
return code;
}ตัวอย่างการใช้งาน
randomCode(); // ผลลัพธ์ = r7nd4l7e86
ฟังก์ชั่นแปลงค่าสีจาก RGB เป็น Hex
function RGBtoHEX(r,g,b)
{
componentToHex = function(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
ตัวอย่างการใช้งาน
RGBtoHEX(255,255,255); // ผลลัพธ์ = #ffffff
ฟังก์ชั่นแปลงค่าสีจาก Hex เป็น RGB
function hexToRGB(hex) {
var r = parseInt((cutHex(hex)).substring(0,2),16);
var g = parseInt((cutHex(hex)).substring(2,4),16);
var b = parseInt((cutHex(hex)).substring(4,6),16);
function cutHex(hex) {return (hex.charAt(0)=="#") ? hex.substring(1,7):hex}
return r + "," + g + "," + b;
}ตัวอย่างการใช้งาน
hexToRGB('#ffffff'); // ผลลัพธ์ = 255,255,255ฟังก์ชั่นคืนค่าทศนิยม 2 ตำแหน่ง
function fixDecimal(num){
return parseFloat(Math.round(num * 100) / 100).toFixed(2);
}ตัวอย่างการใช้งาน
fixDecimal(24.5600); // ผลลัพธ์ = 24.56
ฟังก์ชั่นตรวจสอบการเข้าชมเว็บไซต์ผ่านมือถือ
function isMobile() {
if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i)
){ return true; }else{ return false; }
}ตัวอย่างการใช้งาน
isMobile(); //ผลลัพธ์ = false

