Tidy up some utility functions ~~💞

Convert array-like Object to real array

export function toArray (list, Start) {start = start | | 0 let I = list. The length - start const ret = new Array (I) while (I -) {/ / I - note here, every time returns the value before I minus 1 ret[i] = list[i + start] } return ret }Copy the code

Checks whether the object contains the specified properties

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

Removes an item from an array

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

Make a caching function using closures

Space for time

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

CamelCase characters are converted to Hyphenate format characters

Wraps on top of the previous caching function

Const hyphenateRE = /\B([a-z])/g // match an uppercase character const hyphenate = cached(function (STR) {return str.replace(hyphenateRE, '-$1').toLowerCase() })Copy the code

Uppercase conversion

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

Converts dash – concatenated characters to hump format

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

Use closures to implement functions that are loaded only once

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

Check if it’s a Promise object

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

Simple two dimensional array to one dimensional array

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

To supplement ~ 💖

Day by day over a new leaf