😆一些工具函数-tools

505 阅读1分钟

整理一些工具函数~~💞

将array-like Object转换为real array

export function toArray (list, start) {
    start = start || 0
    let i = list.length - start
    const ret = new Array(i)
    while (i--) { // 注意这里i--,每次返回的是i减1之前的值
        ret[i] = list[i + start]
    }
    return ret
}

检查对象是否包含指定的属性

const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn (obj, key) {
    return hasOwnProperty.call(obj, key)
}

移除数组中某一项

export function remove (arr, item) {
    if (arr.length) {
        const index = arr.indexOf(item)
        if (index > -1) {
            return arr.splice(index, 1)
        }
    }
}

利用闭包做一个缓存函数

空间换时间

export function cached (fn) {
    var cache = Object.create(null)
    return (function cachedFn (str) {
        var hit = cache[str]
        return hit || (cache[str] = fn(str))
    })
}

camelCase字符转换为Hyphenate格式字符

在上一个缓存函数的基础上包装

const hyphenateRE = /\B([A-Z])/g // 匹配一个大写字符
const hyphenate = cached(function (str) {
    return str.replace(hyphenateRE, '-$1').toLowerCase()
})

首字母大写转换

const capitalize = cached(function (str){
    return str.charAt(0).toUpperCase() + str.slice(1)
})

将短横线连接的字符转换为驼峰格式

const camelizeRE = /-(\w)/g
const camelize = cached(function (str) {
    return str.replace(camelizeRE, function(_, c) {
        return c ? c.toUpperCase() : ''
    })
})

利用闭包实现函数只加载一次

function once (fn) {
    let flag = false
    return () => {
        if (!flag) {
            flag = true
            fn(arguments)
        }
    }
}

判断是否是promise对象

function isPromise (obj) {
    return typeof obj.then === 'function' && typeof obj.catch === 'function'
}

简单的二维数组转一维数组

function flatArray(arr) {
    return Array.prototype.concat.apply([], arr)
}

待补充~💖

日日自新