Open preflower opened 2 years ago
/**
* convert Object to match config's string
* @param {Object} o provided Object
* @param {Object} options provide filter, sort, eq, sep config
* @returns match config's string
*/
export function stringify(o, options = {}) {
if (!o) return o
const {
filter = false, // Filter value is [null, '', undefined]'s key
sort = false, // Sort or not
eq = '=', // Connector between key-value pairs
sep = '&' // Separator between key-value pairs
} = options
const ret = []
let keys = Object.keys(o)
if (sort) {
keys = keys.sort()
}
keys.forEach(key => {
if (o[key] === '' || o[key] === null || o[key] === undefined) {
if (!filter) ret.push(key)
} else {
ret.push(`${key}${eq}${o[key]}`)
}
})
return ret.join(sep)
}
/**
* 返回url中指定key的value
* @param {string} url 页面Url
* @param {string} name 指定key
*/
export const getQueryVariable = (url, name = 'sn') => {
url = unescape(url)
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
const r = url
.substring(url.indexOf('?'))
.substr(1)
.match(reg)
if (r != null) return unescape(r[2].replace(/\s+/g, ''))
return null
}
/**
* query 字符串解析器
* @param url 需要被解析的query字符串
* @returns {Object} 解析后的值,以键值对的形式
*/
export function querystring (url: string) {
const parser = /([^=?#&]+)=?([^&]*)/g
const query = url.substring(url.indexOf('?'))
const result: {[k: string]: string} = {}
let part
while ((part = parser.exec(query)) != null) {
const key = decode(part[1])
const value = decode(part[2])
if (key === null || value === null || key in result) continue
result[key] = value
}
return result
}
/**
* 解码 URI 字符串
* @param {String} input 译码后的字符串
* @returns 解码后的字符串
*/
function decode (input: string) {
try {
return decodeURIComponent(input.replace(/\+/g, ' '))
} catch (e) {
return null
}
}
/**
* Promise的形式封装 sleep 函数
* @param delay 延迟时间
* @returns
*/
export function sleep (delay: number = 0): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(undefined)
}, delay)
})
}
日期格式化