@mirari/mp-common
Version:
小程序公共库
121 lines (106 loc) • 3 kB
JavaScript
// 数字补零
function zeroFill (number, targetLength, forceSign) {
const absNumber = '' + Math.abs(number)
const zerosToFill = targetLength - absNumber.length
const sign = number >= 0
return (sign ? (forceSign ? '+' : '') : '-') +
Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber
}
// 实现jquery对象继承,支持深拷贝
function extend () {
const extended = {}
let deep = false
let i = 0
const length = arguments.length
if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]') {
deep = arguments[0]
i++
}
function merge (obj) {
for (let prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') {
extended[prop] = extend(true, extended[prop], obj[prop])
} else {
extended[prop] = obj[prop]
}
}
}
}
for (; i < length; i++) {
let obj = arguments[i]
merge(obj)
}
return extended
}
function wait (time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, time)
})
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach (obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return
}
// Force an array if not already something iterable
if (typeof obj !== 'object' && !isArray(obj)) {
/*eslint no-param-reassign:0*/
obj = [obj]
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj)
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj)
}
}
}
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams (val) {
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams
}
function isArray (val) {
return toString.call(val) === '[object Array]'
}
function isDate (val) {
return toString.call(val) === '[object Date]'
}
function isObject (val) {
return val !== null && typeof val === 'object'
}
export default {
forEach,
isURLSearchParams,
isArray,
isDate,
isObject,
zeroFill,
extend,
wait
}