index.js 8.9 KB
/**
 * 防抖函数
 * @param {Function} func
 * @param {Number} wait
 * @param {Boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result;

    const later = function() {
        // 距上次触发事件间隔
        const last = +new Date() - timestamp;

        // 上次被包装函数被调用时间间隔 last 小于设定的时间间隔 wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null;
            // 如果设定 immediate === true, 因为开始边界已经调用了此处无需调用
            if (!immediate) {
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            }
        }
    }
    return function(...args) {
        context = this;
        timestamp = +new Date();
        const callNow = immediate && !timeout;
        // 如果延时不存在, 重新设定超时
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
            result = func.apply(context, args);
            context = args = null;
        }

        return result;
    }
}

/**
 * 本地过滤器
 * @param {Array} filters
 * @return {*}
 */
// export function mapFilter(filters) {
//     return filters.reduce((result, filter) => {
//         result[filter] = function(...args) {
//             return this.$options.filters[filter](...args);
//         }
//         return result;
//     }, {})
// }

/**
 * 周时间 i18n
 */
export function weekTime(weekTimeText) {
    const text = weekTimeText.replace(/(\d{4})\s[\u4e00-\u9fa5]\s(\d{2})\s[\u4e00-\u9fa5]/, 'Week $2, $1')
    return text || weekTimeText
}

/**
 * 月时间 i18n
 */
export function monthTime(monthTimeText) {
    let monthEn = {
        '01': 'Jan.',
        '02': 'Feb.',
        '03': 'Mar.',
        '04': 'Apr.',
        '05': 'May',
        '06': 'June',
        '07': 'July',
        '08': 'Aug.',
        '09': 'Sept.',
        '10': 'Oct.',
        '11': 'Nov.',
        '12': 'Dec.'
    }
    const matched = monthTimeText.match(/\d+/g)
    const text = monthEn[matched[1]] + ',' + matched[0]
    return text || monthTimeText
}

/**
 * 年时间 i18n
 */
export function yearTime(yearTimeText) {
    const text = 'In ' + yearTime.match(/\d+/g)[0]
    return text || yearTime
}
/**
 * @param {array} actual
 * @returns {array}
 */
export function cleanArray(actual) {
    const newArray = []
    for (let i = 0; i < actual.length; i++) {
        if (actual[i]) {
            newArray.push(actual[i])
        }
    }
    return newArray
}

/**
 * @param {object} obj
 * @returns {object}
 */
export function cleanObject(obj) {
    return Object.keys(obj).reduce((prev, cur) => {
        if (obj[cur] || typeof obj[cur] === 'number') {
            prev[cur] = obj[cur]
        }
        return prev
    }, {})
}

/**
 * @param {object} json
 * @returns {string}
 */
export function param(json) {
    if (!json) return ''
    return cleanArray(
        Object.keys(json).map(key => {
            if (json[key] === undefined) return ''
            return encodeURIComponent(key) + encodeURIComponent('=') + encodeURIComponent(json[key])
        })
    ).join(encodeURIComponent('&'))
}

/**
 * @param {object} json
 * @returns {string}
 */
export function param2(json) {
    if (!json) return ''
    return cleanArray(
        Object.keys(json).map(key => {
            if (json[key] === undefined ||
                json[key] === null
            ) return ''
            return encodeURIComponent(key) + '=' + json[key]
        })
    ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
    const search = url.split('?')[1]
    if (!search) {
        return {}
    }
    return JSON.parse(
        '{"' +
        decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
        '"}'
    )
}

/**
 * 补全表头
 * @param {array} array
 * @returns {arrayObject}
 */
export function ArrayToObject(array) {
    return array.reduce((arr, cur, index) => {
        arr.push({
            prop: `defaultOrg${index}`,
            label: cur
        })
        return arr
    }, [])
}

/**
 * 表格添加平均合计行
 * @param {arrayObject} data
 * @param {array} needRow 增加行数 ['sum', 'avg']
 * @returns {array}
 */
export function addTableRow(data, needRow) {
    const rowLength = data.length
    let copyData = JSON.parse(JSON.stringify(data))
        // 复制第一层数组对象的 key
    const interfaceKey = data[0]
    let newRow = needRow.map(item => {
        return Object.assign({}, interfaceKey, {
            defaultOrg0: item
        })
    })
    copyData.reduce((arr, curr, index) => {
        // if ()
    })
    console.log('newRow', newRow)
}

/**
 * 列复杂计算
 * @param {array} data
 * @param {string} addOption { 'avg' | 'sum' | 'avgAndTotal' }
 * @param {number} startPostion
 * @returns {array} result
 */
export function columnComputed({ data, addOption, startPostion = 0 }) {
    const copyData = JSON.parse(JSON.stringify(data))
    let result = []

    let sums = [],
        avgs = [],
        isAddPos = false,
        averageLen = 0
    for (let rowIndex = 0; rowIndex < copyData.length; rowIndex++) {
        const row = copyData[rowIndex]
        averageLen = 0
        sums[rowIndex] = row.reduce((prev, curr, columnIndex) => {
            isAddPos = startPostion >= 0 ?
                columnIndex > startPostion :
                columnIndex < startPostion

            if (isAddPos) {
                averageLen += 1
                return prev + (
                    isNaN(Number((curr || 0))) ?
                    0 :
                    Number((curr || 0))
                )
            } else {
                return 0
            }
        }, 0)

        if (addOption === 'avg' || addOption === 'avgAndTotal') {
            avgs = sums.map(item => parseFloat((item / averageLen).toFixed(2)))
        }
        if(avgs[rowIndex]){
          result.push(row.concat(avgs[rowIndex], sums[rowIndex]))
        }else{
          result.push(row.concat(sums[rowIndex]))
        }
        
    }

    return result
}

/**
 * 行复杂计算
 * @param {array} data
 * @param {string} addOption { 'avg' | 'sum' | 'avgAndTotal' }
 * @param {number} startPostion
 * @returns {array} result
 */
export function rowComputed({ data, addOption, startPostion = 0 }) {
    const copyData = JSON.parse(JSON.stringify(data))
    let result = []

    let sums = [],
        avgs = [],
        isAddPos = false,
        averageLen = 0
    for (let rowIndex = 0; rowIndex < copyData.length; rowIndex++) {
        const row = copyData[rowIndex]
        averageLen += 1
        row.forEach((column, columnIndex) => {
            isAddPos = startPostion >= 0 ?
                columnIndex > startPostion :
                columnIndex < startPostion

            if (isAddPos) {
                !sums[columnIndex] && (sums[columnIndex] = 0)
                sums[columnIndex] += parseFloat(column || 0)
            } else {
                sums[columnIndex] = '--'
            }

            return column
        })


        if (addOption === 'avg' || addOption === 'avgAndTotal') {
            avgs = sums.map((sum, i) =>
                i > startPostion ?
                parseFloat((sum / averageLen).toFixed(2)) :
                '--'
            )
        }

        result.push(row)
    }

    avgs.length && result.push(avgs)
    sums.length && result.push(sums)

    return result
}

/**
 * 新增平均合计列 curry
 */
export function curryAvgAndSum(columnCallback, rowCallback) {
    return function(...args) {
        const columnRes = columnCallback.apply(this, args)
        const newArgs = Object.assign({}, ...args, { data: columnRes })
        return rowCallback.call(this, newArgs)
    }
}

/**
 * 将表头键值对合并内容数据
 * @param {arrayObject} headData 
 * @param {array} bodyData 
 * @returns {arrayObject}
 */
export function combineHeadAndBody(headData, bodyData) {
    let temp = {}
    let result = []
    for (let rowIndex = 0; rowIndex < bodyData.length; rowIndex++) {
        const row = bodyData[rowIndex]
        temp = row.reduce((ret, curr, columnIndex) => {
            const bodyProp = headData[columnIndex].prop
            ret[bodyProp] = curr === null ? '--' : curr
            return ret
        }, {})
        result.push(temp)
    }

    return result
}

/**
 * 获取当前时间 年月日时分秒
 */
export function getTimer() {
    let date = new Date();
    return date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '' + date.getHours() + '' + date.getMinutes() + '' + date.getSeconds()
}
export function langFormat(val1, val2, val3) {
    let lang = window.localStorage.getItem('lang');
    if (lang == 'zh_CN') {
        return val1
    } else if (lang == 'zh_TW') {
        return val2
    } else {
        return val3
    }
}