作者:YoussefZidan
译者:前端小智
起源:dev
点赞再看,养成习惯
本文
GitHub
https://github.com/qq44924588… 上曾经收录,更多往期高赞文章的分类,也整顿了很多我的文档,和教程材料。欢送 Star 和欠缺,大家面试能够参照考点温习,心愿咱们一起有点货色。
最近开源了一个 Vue 组件,还不够欠缺,欢送大家来一起欠缺它,也心愿大家能给个 star 反对一下,谢谢各位了。
github 地址:https://github.com/qq44924588…
在本文中,分享一些我简直在每个我的项目中都会用到的一些函数。
randomNumber()
获取指定区间的随机数。
**
* 在最小值和最大值之间生成随机整数。* @param {number} min Min number
* @param {number} max Max Number
*/
export const randomNumber = (min = 0, max = 1000) =>
Math.ceil(min + Math.random() * (max - min));
// Example
console.log(randomNumber()); // 97
capitalize()
将字符串的第一个字母变为大写。
/**
* Capitalize Strings.
* @param {string} s String that will be Capitalized
*/
export const capitalize = (s) => {if (typeof s !== "string") return "";
return s.charAt(0).toUpperCase() + s.slice(1);
}
// Example
console.log(capitalize("cat")); // Cat
truncate();
这对于长字符串很有用,特地是在表外部。
/**
* 截断字符串....
* @param {string} 要截断的文本字符串
* @param {number} 截断的长度
*/
export const truncate = (text, num = 10) => {if (text.length > num) {return `${text.substring(0, num - 3)}...`
}
return text;
}
// Example
console.log(truncate("this is some long string to be truncated"));
// this is...
toTop();
滚到到底部,能够通过 behavior
属性指定滚动速度状态。
/**
* Scroll to top
*/
export const toTop = () => {window.scroll({ top: 0, left: 0, behavior: "smooth"});
};
softDeepClone()
这个办法是常常被用到的,因为有了它,咱们能够深度克隆嵌套数组或对象。
不过,这个函数不能与 new Date()
、NaN
、undefined
、function
、Number
、Infinity
等数据类型一起工作。
你想深度克隆上述数据类型,能够应用 lodash 中的 cloneDeep()
函数。
/**
* Deep cloning inputs
* @param {any} input Input
*/
export const softDeepClone= (input) => JSON.parse(JSON.stringify(input));
appendURLParams() & getURLParams()
疾速增加和获取查问字符串的办法,我通常应用它们将分页元数据存储到url
。
/**
* Appen query string and return the value in a query string format.
* @param {string} key
* @param {string} value
*/
export const appendURLParams = (key, value) => {const searchParams = new URLSearchParams(window.location.search).set(key, value);
return searchParams.toString();};
// example
console.log(appendURLParams("name", "youssef")) // name=youssef
/**
* Get param name from URL.
* @param {string} name
*/
export const getURLParams = (name) => new URLSearchParams(window.location.search).get(name);
// Example
console.log(getURLParams(id)) // 5
getInnerHTML()
每当服务器返回一串 HTML 元素时,我都会应用它。
/**
* 获取 HTML 字符串的外部 Text
* @param {string} str A string of HTML
*/
export const getInnerHTML = (str) => str.replace(/(<([^>]+)>)/gi, "");
scrollToHide()
上滚动以显示 HTML 元素,向下滚动以将其暗藏。
/**
* 下滚动时暗藏 HTML 元素。* @param {string} 元素的 id
* @param {string} distance in px ex: "100px"
*/
export const scrollToHide = (id, distance) => {
let prevScrollpos = window.pageYOffset;
window.onscroll = () => {
const currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {document.getElementById(id).style.transform = `translateY(${distance})`;
} else {document.getElementById(id).style.transform = `translateY(-${distance})`;
}
prevScrollpos = currentScrollPos;
};
};
humanFileSize ()
传入字节为单位的文件,返回咱们日常所相熟的单位。
/**
* Converting Bytes to Readable Human File Sizes.
* @param {number} bytes Bytes in Number
*/
export const humanFileSize = (bytes) => {
let BYTES = bytes;
const thresh = 1024;
if (Math.abs(BYTES) < thresh) {return `${BYTES} B`;
}
const units = ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
let u = -1;
const r = 10 ** 1;
do {
BYTES /= thresh;
u += 1;
} while (Math.round(Math.abs(BYTES) * r) / r >= thresh && u < units.length - 1);
return `${BYTES.toFixed(1)} ${units[u]}`;
};
// Example
console.log(humanFileSize(456465465)); // 456.5 MB
getTimes()
你是否有一个 DDL,它每 n 分钟显示一天的工夫? 用这个函数。
/**
* Getting an Array of Times + "AM" or "PM".
* @param {number} minutesInterval
* @param {number} startTime
*/
export const getTimes = (minutesInterval = 15, startTime = 60) => {const times = []; // time array
const x = minutesInterval; // minutes interval
let tt = startTime; // start time
const ap = ["AM", "PM"]; // AM-PM
// loop to increment the time and push results in array
for (let i = 0; tt < 24 * 60; i += 1) {const hh = Math.floor(tt / 60); // getting hours of day in 0-24 format
const mm = tt % 60; // getting minutes of the hour in 0-55 format
times[i] = `${`${hh === 12 ? 12 : hh % 12}`.slice(-2)}:${`0${mm}`.slice(-2)} ${ap[Math.floor(hh / 12)]
}`; // pushing data in array in [00:00 - 12:00 AM/PM format]
tt += x;
}
return times;
};
// Example
console.log(getTimes());
/* [
"1:00 AM",
"1:15 AM",
"1:30 AM",
"1:45 AM",
"2:00 AM",
"2:15 AM",
"2:30 AM",
// ....
]
*/
setLocalItem() & getLocalItem()
让 LocalStorage
具备过期工夫。
/**
* Caching values with expiry date to the LocalHost.
* @param {string} key Local Storage Key
* @param {any} value Local Storage Value
* @param {number} ttl Time to live (Expiry Date in MS)
*/
export const setLocalItem = (key, value, ttl = duration.month) => {const now = new Date();
// `item` is an object which contains the original value
// as well as the time when it's supposed to expire
const item = {
value,
expiry: now.getTime() + ttl,};
localStorage.setItem(key, JSON.stringify(item));
};
/**
* Getting values with expiry date from LocalHost that stored with `setLocalItem`.
* @param {string} key Local Storage Key
*/
export const getLocalItem = (key) => {const itemStr = localStorage.getItem(key);
// if the item doesn't exist, return null
if (!itemStr) {return null;}
const item = JSON.parse(itemStr);
const now = new Date();
// compare the expiry time of the item with the current time
if (now.getTime() > item.expiry) {
// If the item is expired, delete the item from storage
// and return null
localStorage.removeItem(key);
return null;
}
return item.value;
};
formatNumber()
/**
* Format numbers with separators.
* @param {number} num
*/
export const formatNumber = (num) => num.toLocaleString();
// Example
console.log(formatNumber(78899985)); // 78,899,985
咱们还能够增加其余选项来获取其余数字格局,如货币、间隔、权重等。
export const toEGPCurrency = (num) =>
num.toLocaleString("ar-EG", { style: "currency", currency: "EGP"});
export const toUSDCurrency = (num) =>
num.toLocaleString("en-US", { style: "currency", currency: "USD"});
console.log(toUSDCurrency(78899985)); // $78,899,985.00
console.log(toEGPCurrency(78899985)); // ٧٨٬٨٩٩٬٩٨٥٫٠٠ ج.م.
toFormData()
每当我须要向服务器发送文件时,我就应用这个函数。
/**
* Convert Objects to Form Data Format.
* @param {object} obj
*/
export const toFormData = (obj) => {const formBody = new FormData();
Object.keys(obj).forEach((key) => {formBody.append(key, obj[key])
})
return formBody;
}
getScreenWidth()
获取一个示意屏幕宽度的字符串。
/**
* Detect screen width and returns a string representing the width of the screen.
*/
export const getScreenWidth = () => {
const screenWidth = window.screen.width;
if (screenWidth <= 425) return "mobile";
if (screenWidth <= 768) return "tablet";
if (screenWidth <= 1024) return "laptopSm";
if (screenWidth <= 1440) return "laptopLg";
if (screenWidth <= 2560) return "HD";
return screenWidth;
};
查看数组中的每个元素是否存在于另一个数组中。
export const containsAll = (baseArr, arr) => {
let all = false;
for (let i = 0; i < arr.length; i += 1) {if (baseArr.includes(arr[i])) {all = true;} else {
all = false;
return all;
}
}
return all;
};
你还有应用其余有用的函数吗? 在评论里分享一下怎么样?
完~,我是小智,我要去刷碗去了。
代码部署后可能存在的 BUG 没法实时晓得,预先为了解决这些 BUG,花了大量的工夫进行 log 调试,这边顺便给大家举荐一个好用的 BUG 监控工具 Fundebug。
原文:https://dev.to/youssefzidan/j…
交换
文章每周继续更新,能够微信搜寻「大迁世界」第一工夫浏览和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 曾经收录,整顿了很多我的文档,欢送 Star 和欠缺,大家面试能够参照考点温习,另外关注公众号,后盾回复 福利,即可看到福利,你懂的。