摘要:更新單元測試,已使用,,,使用測試覆蓋率,并集成配合來做持續(xù)化構(gòu)建,可以參考本項目的配置文件和的配置文件。判斷是否然后記得在文件中暴露函數(shù)單元測試在文件新建測試用例然后記得在中引入之前創(chuàng)建的測試用例腳本。
前言
作為戰(zhàn)斗在業(yè)務(wù)一線的前端,要想少加班,就要想辦法提高工作效率。這里提一個小點,我們在業(yè)務(wù)開發(fā)過程中,經(jīng)常會重復(fù)用到日期格式化、url參數(shù)轉(zhuǎn)對象、瀏覽器類型判斷、節(jié)流函數(shù)等一類函數(shù),這些工具類函數(shù),基本上在每個項目都會用到,為避免不同項目多次復(fù)制粘貼的麻煩,我們可以統(tǒng)一封裝,發(fā)布到npm,以提高開發(fā)效率。
這里,筆者已經(jīng)封裝并發(fā)布了自己的武器庫 outils,如果你對本項目感興趣,歡迎 star 本項目。當(dāng)然你也可以在本項目的基礎(chǔ)上封裝自己的武器庫。
常用函數(shù)匯總
這里先分類整理下,之前項目中多次用到的工具函數(shù)。
1.Array
1.1 arrayEqual
/**
@desc 判斷兩個數(shù)組是否相等
@param {Array} arr1
@param {Array} arr2
@return {Boolean}
*/
function arrayEqual(arr1, arr2) {
if (arr1 === arr2) return true; if (arr1.length != arr2.length) return false; for (var i = 0; i < arr1.length; ++i) { if (arr1[i] !== arr2[i]) return false; } return true;
}
2.Class
2.1 addClass
/**
@desc 為元素添加class
@param {HTMLElement} ele
@param {String} cls
*/
var hasClass = require("./hasClass");
function addClass(ele, cls) {
if (!hasClass(ele, cls)) { ele.className += " " + cls; }
}
2.2 hasClass
/**
@desc 判斷元素是否有某個class
@param {HTMLElement} ele
@param {String} cls
@return {Boolean}
*/
function hasClass(ele, cls) {
return (new RegExp("(s|^)" + cls + "(s|$)")).test(ele.className);
}
2.3 removeClass
/**
@desc 為元素移除class
@param {HTMLElement} ele
@param {String} cls
*/
var hasClass = require("./hasClass");
function removeClass(ele, cls) {
if (hasClass(ele, cls)) { var reg = new RegExp("(s|^)" + cls + "(s|$)"); ele.className = ele.className.replace(reg, " "); }
}
3.Cookie
3.1 getCookie
/**
@desc 根據(jù)name讀取cookie
@param {String} name
@return {String}
*/
function getCookie(name) {
var arr = document.cookie.replace(/s/g, "").split(";"); for (var i = 0; i < arr.length; i++) { var tempArr = arr[i].split("="); if (tempArr[0] == name) { return decodeURIComponent(tempArr[1]); } } return "";
}
3.2 removeCookie
var setCookie = require("./setCookie");
/**
@desc 根據(jù)name刪除cookie
@param {String} name
*/
function removeCookie(name) {
// 設(shè)置已過期,系統(tǒng)會立刻刪除cookie setCookie(name, "1", -1);
}
3.3 setCookie
/**
@desc 設(shè)置Cookie
@param {String} name
@param {String} value
@param {Number} days
*/
function setCookie(name, value, days) {
var date = new Date(); date.setDate(date.getDate() + days); document.cookie = name + "=" + value + ";expires=" + date;
}
4.Device
4.1 getExplore
/**
@desc 獲取瀏覽器類型和版本
@return {String}
*/
function getExplore() {
var sys = {}, ua = navigator.userAgent.toLowerCase(), s; (s = ua.match(/rv:([d.]+)) like gecko/)) ? sys.ie = s[1]: (s = ua.match(/msie ([d.]+)/)) ? sys.ie = s[1] : (s = ua.match(/edge/([d.]+)/)) ? sys.edge = s[1] : (s = ua.match(/firefox/([d.]+)/)) ? sys.firefox = s[1] : (s = ua.match(/(?:opera|opr).([d.]+)/)) ? sys.opera = s[1] : (s = ua.match(/chrome/([d.]+)/)) ? sys.chrome = s[1] : (s = ua.match(/version/([d.]+).*safari/)) ? sys.safari = s[1] : 0; // 根據(jù)關(guān)系進行判斷 if (sys.ie) return ("IE: " + sys.ie) if (sys.edge) return ("EDGE: " + sys.edge) if (sys.firefox) return ("Firefox: " + sys.firefox) if (sys.chrome) return ("Chrome: " + sys.chrome) if (sys.opera) return ("Opera: " + sys.opera) if (sys.safari) return ("Safari: " + sys.safari) return "Unkonwn"
}
4.2 getOS
/**
@desc 獲取操作系統(tǒng)類型
@return {String}
*/
function getOS() {
var userAgent = "navigator" in window && "userAgent" in navigator && navigator.userAgent.toLowerCase() || ""; var vendor = "navigator" in window && "vendor" in navigator && navigator.vendor.toLowerCase() || ""; var appVersion = "navigator" in window && "appVersion" in navigator && navigator.appVersion.toLowerCase() || ""; if (/mac/i.test(appVersion)) return "MacOSX" if (/win/i.test(appVersion)) return "windows" if (/linux/i.test(appVersion)) return "linux" if (/iphone/i.test(userAgent) || /ipad/i.test(userAgent) || /ipod/i.test(userAgent)) "ios" if (/android/i.test(userAgent)) return "android" if (/win/i.test(appVersion) && /phone/i.test(userAgent)) return "windowsPhone"
}
5.Dom
5.1 getScrollTop
/**
@desc 獲取滾動條距頂部的距離
*/
function getScrollTop() {
return (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
}
5.2 offset
/**
@desc 獲取一個元素的距離文檔(document)的位置,類似jQ中的offset()
@param {HTMLElement} ele
@returns { {left: number, top: number} }
*/
function offset(ele) {
var pos = { left: 0, top: 0 }; while (ele) { pos.left += ele.offsetLeft; pos.top += ele.offsetTop; ele = ele.offsetParent; }; return pos;
}
5.3 scrollTo
var getScrollTop = require("./getScrollTop");
var setScrollTop = require("./setScrollTop");
var requestAnimFrame = (function () {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); };
})();
/**
@desc 在${duration}時間內(nèi),滾動條平滑滾動到${to}指定位置
@param {Number} to
@param {Number} duration
*/
function scrollTo(to, duration) {
if (duration < 0) { setScrollTop(to); return } var diff = to - getScrollTop(); if (diff === 0) return var step = diff / duration * 10; requestAnimationFrame( function () { if (Math.abs(step) > Math.abs(diff)) { setScrollTop(getScrollTop() + diff); return; } setScrollTop(getScrollTop() + step); if (diff > 0 && getScrollTop() >= to || diff < 0 && getScrollTop() <= to) { return; } scrollTo(to, duration - 16); });
}
5.4 setScrollTop
/**
@desc 設(shè)置滾動條距頂部的距離
*/
function setScrollTop(value) {
window.scrollTo(0, value); return value;
}
6.Keycode
6.1 getKeyName
var keyCodeMap = {
8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "Caps Lock", 27: "Escape", 32: "Space", 33: "Page Up", 34: "Page Down", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 42: "Print Screen", 45: "Insert", 46: "Delete", 48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9", 65: "A", 66: "B", 67: "C", 68: "D", 69: "E", 70: "F", 71: "G", 72: "H", 73: "I", 74: "J", 75: "K", 76: "L", 77: "M", 78: "N", 79: "O", 80: "P", 81: "Q", 82: "R", 83: "S", 84: "T", 85: "U", 86: "V", 87: "W", 88: "X", 89: "Y", 90: "Z", 91: "Windows", 93: "Right Click", 96: "Numpad 0", 97: "Numpad 1", 98: "Numpad 2", 99: "Numpad 3", 100: "Numpad 4", 101: "Numpad 5", 102: "Numpad 6", 103: "Numpad 7", 104: "Numpad 8", 105: "Numpad 9", 106: "Numpad *", 107: "Numpad +", 109: "Numpad -", 110: "Numpad .", 111: "Numpad /", 112: "F1", 113: "F2", 114: "F3", 115: "F4", 116: "F5", 117: "F6", 118: "F7", 119: "F8", 120: "F9", 121: "F10", 122: "F11", 123: "F12", 144: "Num Lock", 145: "Scroll Lock", 182: "My Computer", 183: "My Calculator", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "", 221: "]", 222: """
};
/**
@desc 根據(jù)keycode獲得鍵名
@param {Number} keycode
@return {String}
*/
function getKeyName(keycode) {
if (keyCodeMap[keycode]) { return keyCodeMap[keycode]; } else { console.log("Unknow Key(Key Code:" + keycode + ")"); return ""; }
};
7.Object
7.1 deepClone
/**
@desc 深拷貝,支持常見類型
@param {Any} values
*/
function deepClone(values) {
var copy; // Handle the 3 simple types, and null or undefined if (null == values || "object" != typeof values) return values; // Handle Date if (values instanceof Date) { copy = new Date(); copy.setTime(values.getTime()); return copy; } // Handle Array if (values instanceof Array) { copy = []; for (var i = 0, len = values.length; i < len; i++) { copy[i] = deepClone(values[i]); } return copy; } // Handle Object if (values instanceof Object) { copy = {}; for (var attr in values) { if (values.hasOwnProperty(attr)) copy[attr] = deepClone(values[attr]); } return copy; } throw new Error("Unable to copy values! Its type isn"t supported.");
}
7.2 isEmptyObject
/**
@desc 判斷obj是否為空
@param {Object} obj
@return {Boolean}
*/
function isEmptyObject(obj) {
if (!obj || typeof obj !== "object" || Array.isArray(obj)) return false return !Object.keys(obj).length
}
8.Random
8.1 randomColor
/**
@desc 隨機生成顏色
@return {String}
*/
function randomColor() {
return "#" + ("00000" + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
}
8.2 randomNum?
/**
@desc 生成指定范圍隨機數(shù)
@param {Number} min
@param {Number} max
@return {Number}
*/
function randomNum(min, max) {
return Math.floor(min + Math.random() * (max - min));
}
9.Regexp
9.1 isEmail
/**
@desc 判斷是否為郵箱地址
@param {String} str
@return {Boolean}
*/
function isEmail(str) {
return /w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*/.test(str);
}
9.2 isIdCard
/**
@desc 判斷是否為身份證號
@param {String|Number} str
@return {Boolean}
*/
function isIdCard(str) {
return /^(^[1-9]d{7}((0d)|(1[0-2]))(([0|1|2]d)|3[0-1])d{3}$)|(^[1-9]d{5}[1-9]d{3}((0d)|(1[0-2]))(([0|1|2]d)|3[0-1])((d{4})|d{3}[Xx])$)$/.test(str)
}
9.3 isPhoneNum
/**
@desc 判斷是否為手機號
@param {String|Number} str
@return {Boolean}
*/
function isPhoneNum(str) {
return /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(str)
}
9.4 isUrl
/**
@desc 判斷是否為URL地址
@param {String} str
@return {Boolean}
*/
function isUrl(str) {
return /[-a-zA-Z0-9@:%._+~#=]{2,256}.[a-z]{2,6}([-a-zA-Z0-9@:%_+.~#?&//=]*)/i.test(str);
}
10.String
10.1 digitUppercase
/**
@desc 現(xiàn)金額轉(zhuǎn)大寫
@param {Number} n
@return {String}
*/
function digitUppercase(n) {
var fraction = ["角", "分"]; var digit = [ "零", "壹", "貳", "叁", "肆", "伍", "陸", "柒", "捌", "玖" ]; var unit = [ ["元", "萬", "億"], ["", "拾", "佰", "仟"] ]; var head = n < 0 ? "欠" : ""; n = Math.abs(n); var s = ""; for (var i = 0; i < fraction.length; i++) { s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, ""); } s = s || "整"; n = Math.floor(n); for (var i = 0; i < unit[0].length && n > 0; i++) { var p = ""; for (var j = 0; j < unit[1].length && n > 0; j++) { p = digit[n % 10] + unit[1][j] + p; n = Math.floor(n / 10); } s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s; } return head + s.replace(/(零.)*零元/, "元") .replace(/(零.)+/g, "零") .replace(/^整$/, "零元整");
};
11.Support
11.1 isSupportWebP
/**
@desc 判斷瀏覽器是否支持webP格式圖片
@return {Boolean}
*/
function isSupportWebP() {
return !![].map && document.createElement("canvas").toDataURL("image/webp").indexOf("data:image/webp") == 0;
}
12.Time
12.1 formatPassTime
/**
@desc 格式化${startTime}距現(xiàn)在的已過時間
@param {Date} startTime
@return {String}
*/
function formatPassTime(startTime) {
var currentTime = Date.parse(new Date()), time = currentTime - startTime, day = parseInt(time / (1000 * 60 * 60 * 24)), hour = parseInt(time / (1000 * 60 * 60)), min = parseInt(time / (1000 * 60)), month = parseInt(day / 30), year = parseInt(month / 12); if (year) return year + "年前" if (month) return month + "個月前" if (day) return day + "天前" if (hour) return hour + "小時前" if (min) return min + "分鐘前" else return "剛剛"
}
12.2 formatRemainTime
/**
@desc 格式化現(xiàn)在距${endTime}的剩余時間
@param {Date} endTime
@return {String}
*/
function formatRemainTime(endTime) {
var startDate = new Date(); //開始時間 var endDate = new Date(endTime); //結(jié)束時間 var t = endDate.getTime() - startDate.getTime(); //時間差 var d = 0, h = 0, m = 0, s = 0; if (t >= 0) { d = Math.floor(t / 1000 / 3600 / 24); h = Math.floor(t / 1000 / 60 / 60 % 24); m = Math.floor(t / 1000 / 60 % 60); s = Math.floor(t / 1000 % 60); } return d + "天 " + h + "小時 " + m + "分鐘 " + s + "秒";
}
13.Url
13.1 parseQueryString
/**
@desc url參數(shù)轉(zhuǎn)對象
@param {String} url default: window.location.href
@return {Object}
*/
function parseQueryString(url) {
url = url == null ? window.location.href : url var search = url.substring(url.lastIndexOf("?") + 1) if (!search) { return {} } return JSON.parse("{"" + decodeURIComponent(search).replace(/"/g, """).replace(/&/g, "","").replace(/=/g, "":"") + ""}")
}
13.2 stringfyQueryString
/**
@desc 對象序列化
@param {Object} obj
@return {String}
*/
function stringfyQueryString(obj) {
if (!obj) return ""; var pairs = []; for (var key in obj) { var value = obj[key]; if (value instanceof Array) { for (var i = 0; i < value.length; ++i) { pairs.push(encodeURIComponent(key + "[" + i + "]") + "=" + encodeURIComponent(value[i])); } continue; } pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key])); } return pairs.join("&");
}
14.Function
14.1 throttle
/**
@desc 函數(shù)節(jié)流。
適用于限制resize和scroll等函數(shù)的調(diào)用頻率
*
@param {Number} delay 0 或者更大的毫秒數(shù)。 對于事件回調(diào),大約100或250毫秒(或更高)的延遲是最有用的。
@param {Boolean} noTrailing 可選,默認為false。
如果noTrailing為true,當(dāng)節(jié)流函數(shù)被調(diào)用,每過delay毫秒callback也將執(zhí)行一次。
如果noTrailing為false或者未傳入,callback將在最后一次調(diào)用節(jié)流函數(shù)后再執(zhí)行一次.
(延遲delay毫秒之后,節(jié)流函數(shù)沒有被調(diào)用,內(nèi)部計數(shù)器會復(fù)位)
@param {Function} callback 延遲毫秒后執(zhí)行的函數(shù)。this上下文和所有參數(shù)都是按原樣傳遞的,
執(zhí)行去節(jié)流功能時,調(diào)用callback。
@param {Boolean} debounceMode 如果debounceMode為true,clear在delayms后執(zhí)行。
如果debounceMode是false,callback在delay ms之后執(zhí)行。
*
@return {Function} 新的節(jié)流函數(shù)
*/
function throttle(delay, noTrailing, callback, debounceMode) {
// After wrapper has stopped being called, this timeout ensures that // `callback` is executed at the proper times in `throttle` and `end` // debounce modes. var timeoutID; // Keep track of the last time `callback` was executed. var lastExec = 0; // `noTrailing` defaults to falsy. if (typeof noTrailing !== "boolean") { debounceMode = callback; callback = noTrailing; noTrailing = undefined; } // The `wrapper` function encapsulates all of the throttling / debouncing // functionality and when executed will limit the rate at which `callback` // is executed. function wrapper() { var self = this; var elapsed = Number(new Date()) - lastExec; var args = arguments; // Execute `callback` and update the `lastExec` timestamp. function exec() { lastExec = Number(new Date()); callback.apply(self, args); } // If `debounceMode` is true (at begin) this is used to clear the flag // to allow future `callback` executions. function clear() { timeoutID = undefined; } if (debounceMode && !timeoutID) { // Since `wrapper` is being called for the first time and // `debounceMode` is true (at begin), execute `callback`. exec(); } // Clear any existing timeout. if (timeoutID) { clearTimeout(timeoutID); } if (debounceMode === undefined && elapsed > delay) { // In throttle mode, if `delay` time has been exceeded, execute // `callback`. exec(); } else if (noTrailing !== true) { // In trailing throttle mode, since `delay` time has not been // exceeded, schedule `callback` to execute `delay` ms after most // recent execution. // // If `debounceMode` is true (at begin), schedule `clear` to execute // after `delay` ms. // // If `debounceMode` is false (at end), schedule `callback` to // execute after `delay` ms. timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay); } } // Return the wrapper function. return wrapper;
};
14.2 debounce
/**
@desc 函數(shù)防抖
與throttle不同的是,debounce保證一個函數(shù)在多少毫秒內(nèi)不再被觸發(fā),只會執(zhí)行一次,
要么在第一次調(diào)用return的防抖函數(shù)時執(zhí)行,要么在延遲指定毫秒后調(diào)用。
@example 適用場景:如在線編輯的自動存儲防抖。
@param {Number} delay 0或者更大的毫秒數(shù)。 對于事件回調(diào),大約100或250毫秒(或更高)的延遲是最有用的。
@param {Boolean} atBegin 可選,默認為false。
如果atBegin為false或未傳入,回調(diào)函數(shù)則在第一次調(diào)用return的防抖函數(shù)后延遲指定毫秒調(diào)用。
如果`atBegin`為true,回調(diào)函數(shù)則在第一次調(diào)用return的防抖函數(shù)時直接執(zhí)行
@param {Function} callback 延遲毫秒后執(zhí)行的函數(shù)。this上下文和所有參數(shù)都是按原樣傳遞的,
執(zhí)行去抖動功能時,,調(diào)用callback。
*
@return {Function} 新的防抖函數(shù)。
*/
var throttle = require("./throttle");
function debounce(delay, atBegin, callback) {
return callback === undefined ? throttle(delay, atBegin, false) : throttle(delay, callback, atBegin !== false);
};
封裝
除了對上面這些常用函數(shù)進行封裝, 最重要的是支持合理化的引入,這里我們使用webpack統(tǒng)一打包成UMD 通用模塊規(guī)范,支持webpack、RequireJS、SeaJS等模塊加載器,亦或直接通過
var OS = outils.getOS()
注意: 本倉庫代碼會持續(xù)更新,如果你需要不同版本的增量壓縮包或源碼,請到 github Release 頁面下載對應(yīng)版本號的代碼。
2.Webpack、RequireJS、SeaJS等模塊加載器
先使用npm安裝outils。
$ npm install --save-dev outils
// 完整引入
const outils = require("outils")
const OS = outils.getOS()
推薦使用方法
// 按需引入require("outils/<方法名>")
const getOS = require("outils/getOS")
const OS = getOS()
當(dāng)然,你的開發(fā)環(huán)境有babel編譯ES6語法的話,也可以這樣使用:
import getOS from "outils/getOS"
// 或
import { getOS } from "outils";
總結(jié)
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/92575.html
摘要:因為用戶不用在第一次進入應(yīng)用時下載所有代碼,用戶能更快的看到頁面并與之交互。譯高階函數(shù)利用和來編寫更易維護的代碼高階函數(shù)可以幫助你增強你的,讓你的代碼更具有聲明性。知道什么時候和怎樣使用高階函數(shù)是至關(guān)重要的。 Vue 折騰記 - (10) 給axios做個挺靠譜的封裝(報錯,鑒權(quán),跳轉(zhuǎn),攔截,提示) 稍微改改都能直接拿來用~~~喲吼吼,喲吼吼..... 如何無痛降低 if else 面...
摘要:一直對抱有敬畏的態(tài)度,也沒有一直深入學(xué)習(xí)。當(dāng)學(xué)到各種框架的時候才發(fā)現(xiàn)力不從心,感覺到了基礎(chǔ)的重要性,重新認真的系統(tǒng)的學(xué)習(xí)一下。 一直對javscript抱有敬畏的態(tài)度,也沒有一直深入學(xué)習(xí)。當(dāng)學(xué)到各種js框架的時候才發(fā)現(xiàn)力不從心,感覺到了javascript基礎(chǔ)的重要性,重新認真的系統(tǒng)的學(xué)習(xí)一下。showImg(http://static.xiaomo.info/images/javas...
摘要:是什么是一個特別的關(guān)鍵字,是自動定義在所有函數(shù)和全局的作用域中。是在運行時綁定的,而不是聲明時綁定的。小結(jié)的指向取決于函數(shù)執(zhí)行時的塊級上下文 This This是什么:this是一個特別的關(guān)鍵字,是自動定義在所有函數(shù)和全局的作用域中。this是在運行時綁定的,而不是聲明時綁定的。 為什么要有this假設(shè)不存在this關(guān)鍵字,那么對于一個函數(shù)根據(jù)不同上下文背景下的復(fù)用就用傳入?yún)?shù) ...
摘要:上一篇前端常用插件工具類庫匯總上內(nèi)容摘要動畫庫滾動庫輪播圖滾屏彈出框消息通知下拉框級聯(lián)選擇器顏色選擇器時間日期處理表單驗證分頁插件本篇延續(xù)上一篇的內(nèi)容繼續(xù)給大家?guī)硪幌盗嘘P(guān)于前端插件工具類的內(nèi)容。 showImg(https://segmentfault.com/img/bVbjsMh?w=900&h=383); 前言 對本文感興趣可以先加個收藏,也可以轉(zhuǎn)發(fā)分享給身邊的小伙伴,以后遇到...
閱讀 2556·2021-10-11 10:58
閱讀 1041·2019-08-29 13:58
閱讀 1675·2019-08-26 13:32
閱讀 840·2019-08-26 10:40
閱讀 3268·2019-08-26 10:18
閱讀 1764·2019-08-23 14:18
閱讀 1116·2019-08-23 10:54
閱讀 443·2019-08-22 18:39