Business development often deals with data. In order to improve development efficiency and save development cycle, the following tool classes are what you say you need.
1. Time Formatting
/** * @params time time stamp * @params cFormat Format type {y}-{m}-{d} {h}:{i}:{s} * Where y | m | d | h | m | s | a denotes year | month | day | time | minutes | seconds | weeks, respectively * Support {y}-{m}-{d}, {y} year {m} month {d} day */ export function formatTime (time, cFormat) { if (arguments.length === 0) { return null } const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' let date if (typeof time === 'object') { date = time } else { if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) { time = parseInt(time) } if ((typeof time === 'number') && (time.toString().length === 10)) { time = time * 1000 } date = new Date(time) } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() } const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => { let value = formatObj[key] if (key === 'a') { return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][value] } if (result.length > 0 && value < 10) { value = '0' + value } return value || 0 }) return timeStr }
:::tip
formatTime(1568171857433) --> 2019-09-11 11:17:37
formatTime(1568171857433, '{y}-{m}-{d}') --> 2019-09-11
formatTime(1568171857433, '{h}:{i}:{s}') --> 11:17:37
FormatTime (1568171857433,'{a}') - > Wednesday
FormatTime (1568171857433,'{y} year {m} month {d} day') > 11 September 2019
formatTime(128000, '{i}:{s}') --> 02:08
:::
2. Get the response timestamp in days
/** * @params num > 0 Get time for the future * @params num < 0 Get the Past Time */ export function setDate(num) { return Date.now() + num * 24 * 60 * 60 * 1000 }
::: tip
12 hours ago - > setDate (-.5)
24 hours ago - > setDate (- 1)
Three days later - > setDate (3)
:::
3. Get the parameters in the URL
export function getUrlParams (param) { let reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)'), result = location.search.substring(1).match(reg) return result && result[2] }
::: tip
Give an example: https://xxx.com?id=352&valiag...
getUrlParams(id) --> 352
:::
4. Deep copy
export function deepClone (source) { if (!source && typeof source !== 'object') { throw new Error('error arguments') } const targetObj = source.constructor === Array ? [] : {} Object.keys(source).forEach((keys) => { if (source[keys] && typeof source[keys] === 'object') { targetObj[keys] = deepClone(source[keys]) } else { targetObj[keys] = source[keys] } }) return targetObj }
5. Change the name of the hump to the middle horizontal bar
export function toMiddleLine (str) { let temp = str.replace(/[A-Z]/g, function (match) { return '-' + match.toLowerCase() }) // If the initials are capitalized, there will be one more replace - - which needs to be removed here. if (temp.slice(0, 1) === '-') { temp = temp.slice(1) } return temp }
::: tip
toMiddleLine(PlInputGroup) --> pl-input-group
:::
6. Judgment of Mobile Operating Environment
BrowserType = { isAndroid: Boolean(navigator.userAgent.match(/android/ig)), isIPhone: Boolean(navigator.userAgent.match(/iphone|ipod/ig)), isIPad: Boolean(navigator.userAgent.match(/ipad/ig)), isWeiChat: Boolean(navigator.userAgent.match(/MicroMessenger/ig)), isAli: Boolean(navigator.userAgent.match(/AlipayClient/ig)), isPhone: Boolean(/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) }
Are browsers Android / Apple & iPad & WeChat & Alipay & mobile terminal
7. Dimension Reduction of Multidimensional Arrays
Two-dimensional array
export function toTwoArray(arr) { return Array.prototype.concat.apply([], arr) }
:::tip
let arr = [ [1], [2], [3] ]
toTwoArray(arr) --> [1, 2, 3]
:::
Multidimensional array
The flat() method recursively traverses the array at a specified depth, and returns by merging all elements with elements in the traversed subarray into a new array.
flat has compatibility problems, but the mobile phone has little problems. Browser side is incompatible with edge, using Infinity as depth to expand nested arrays of arbitrary depth
:::tip
var arr1 = [1, 2, [3, 4]];
arr1.flat();
--> [1, 2, 3, 4]
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
--> [1, 2, 3, 4, [5, 6]]
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
--> [1, 2, 3, 4, 5, 6]
// Expand nested arrays of arbitrary depth using Infinity as depth
arr3.flat(Infinity);
--> [1, 2, 3, 4, 5, 6]
:::
8. Maximum and Minimum Array
// minimum value export function minimum (array) { return Math.min.apply(Math, array) } // Maximum value export function maximum (array) { return Math.max.apply(Math, array) }
:::tip
minimum([0, 1, 4, 9]); --> 0
maximum([0, 1, 4, 9]); --> 9
:::
9. Shake-proof & Throttle
Anti shake
function debounce (func, delay) { let timer return (...args) => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { func.apply(this, args) }, delay) } }
throttle
function throttle(func, wait) { let previous = 0 return function() { let now = Date.now() let context = this let args = arguments if (now - previous > wait) { func.apply(context, args) previous = now } } }
10. Generate a random number within the value
export const rand = (function () { const today = new Date() let seed = today.getTime() // generate function generated() { seed = (seed * 9301 + 49297) % 233280 return seed / (233280.0) } return function rand(number) { return Math.ceil(generated(seed) * number) } })()
11. Digital Unit Conversion
export const transNumber = (num) => { let numStr = parseInt(num).toString() if (numStr.length < 5) { // Direct return within 10,000 return num } else if (numStr.length > 8) { // More than 8 digits is 100 million let decimal = numStr.substring(numStr.length - 8) return parseInt(parseInt(num / 100000000) + '.' + decimal) + 'Billion' } else { let decimal = numStr.substring(numStr.length - 4) return parseInt(parseInt(num / 10000) + '.' + decimal) + 'ten thousand' } }
12. Millisecond to Standard Minutes
You can do this with formatTime(), the first method above.
// Millisecond to standard minute export function standardTime (second) { second = Math.floor(second) let minute = Math.floor(second / 60) second = second - minute * 60 return minute + ':' + formatTime(second) } // Format minutes and seconds export function formatMiniTime (time) { let timeStr = '00' if (time > 0 && time < 10) { timeStr = '0' + time; } else if (time >= 10) { timeStr = time } return timeStr }