wkitd/src/utils.js

116 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-08-10 19:59:02 +08:00
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/08/10 10:07:51
*/
2023-08-14 15:07:02 +08:00
const encode = encodeURIComponent
const decode = decodeURIComponent
2023-08-10 19:59:02 +08:00
export function noop() {}
export function hideProp(host, name, value) {
Object.defineProperty(host, name, {
value,
enumerable: false,
writable: true
})
}
// 判定A标签的target属性是否指向自身
export function targetIsThisWindow(target) {
if (
!target ||
target === window.name ||
target === '_self' ||
(target === 'top' && window == window.top)
) {
return true
}
return false
}
2023-08-14 15:07:02 +08:00
/**
* query 序列化
*/
function serialize(p, obj, callback) {
var k
if (Array.isArray(obj)) {
obj.forEach(function (it, i) {
k = p ? `${p}[${Array.isArray(it) ? i : ''}]` : i
if (typeof it === 'object') {
serialize(k, it, callback)
} else {
callback(k, it)
}
})
} else {
for (let i in obj) {
k = p ? `${p}[${i}]` : i
if (typeof obj[i] === 'object') {
serialize(k, obj[i], callback)
} else {
callback(k, obj[i])
}
}
}
}
/**
* 将url query转回json对象
*/
export function query2object(str = '') {
let params = new URLSearchParams(str)
let output = Object.create(null)
for (let [_k, _v] of params.entries()) {
let k = decode(_k)
let v = decode(_v)
let isArray = 0
if (/(\w+)\[(\w*?)\]/.test(k)) {
let k1 = RegExp.$1
let k2 = RegExp.$2
k = k1
if (!k2 || +k2 === +k2) {
v = [v]
isArray |= 2
} else {
isArray |= 1
v = { [k2]: v }
}
}
if (output[k]) {
if (isArray & 2) {
output[k] = output[k].concat(v)
} else {
Object.assign(output[k], v)
}
} else {
output[k] = v
}
}
return output
}
/**
* 将json数据转成 url query字符串
*/
export function object2query(obj = {}) {
if (!obj || typeof obj === 'string' || typeof obj === 'number') {
return obj
}
let output = []
let query = function (k, v) {
output.push(k + '=' + encode(v))
}
if (typeof obj === 'object') {
serialize('', obj, query)
}
return output.join('&')
}