zoukankan      html  css  js  c++  java
  • tool.js日常工具方法

    // 基础公共方法
    
    /**
     * 将数据转化成数组 eg: 1 => [1] / [1] => [1]
     * @param {Array} arr 数组或单个数据
     */
    export const toArray = arr => [].concat(arr);
    
    /**
     * 数组去重
     * @param {Array} arr 要去重的数组
     * @returns {Array} 去重后的数组
     */
    export function uniqueArr (arr) {
      if (arr && arr instanceof Array) {
        return new Array(...new Set(arr));
      }
      return arr;
    }
    
    /**
     * 小于10的数字,前边加个0
     * @param {Number} num 要转换的数字
     * @returns {String} 转换后的数字
     */
    export function addZero (num) {
      return (num < 10 ? '0' : '') + num;
    }
    
    /**
     * 连字符转驼峰
     * @param {String} data 要转换的数据
     */
    export function hyphenToHump (data) {
      if (typeof data === 'string') {
        return data.replace(/-(w)/g, (...args) => args[1].toUpperCase());
      }
      return data;
    }
    /**
     * 驼峰转连字符
     * @param {String} data 要转换的数据
     */
    export function humpToHyphen (data) {
      if (typeof data === 'string') {
        return data.replace(/([A-Z])/g, '-$1').toLowerCase();
      }
      return data;
    }
    
    /**
     * 格式化时间 将 Date 转化为指定格式的String
     * @param {Date} date 要转换的数据
     * @param {String} fmt 指定格式 默认为 'yyyy-MM-dd hh:mm:ss'
     */
    export function formatDate (date = new Date(), fmt = 'yyyy-MM-dd hh:mm:ss') {
      const that = new Date(date);
      var o = {
        'M+': that.getMonth() + 1, // 月份
        'd+': that.getDate(), // 日
        'h+': that.getHours(), // 小时
        'm+': that.getMinutes(), // 分
        's+': that.getSeconds(), // 秒
        'q+': Math.floor((that.getMonth() + 3) / 3), // 季度
        S: that.getMilliseconds() // 毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (that.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
      }
      return fmt;
    }
    
    /**
     * 每隔一段时间判断条件是否满足,条件满足时执行函数
     * @param {Function} callFunc 条件满足时执行的函数
     * @param {Function} condition 获取条件是否满足 默认为满足
     * @param {Number} interval 时间间隔 单位毫秒 默认为 100ms
     */
    export function delay (callFunc, condition = () => true, interval = 100) {
      const _delay = (callFunc, condition, interval) => {
        let TIMER = null;
        TIMER = setTimeout(() => {
          if (condition()) {
            clearTimeout(TIMER);
            callFunc();
          } else {
            _delay(callFunc, condition, interval);
          }
        }, interval);
      };
      if (condition()) { // 先判断是否满足条件
        callFunc();
      } else {
        _delay(callFunc, condition, interval);
      }
    }
    
    // 节流
    export const throttle = (fn, delay = 500) => {
      let timer = null;
      return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.bind(this)(arguments);
        }, delay);
      };
    };
    
    /**
     * 安全的执行方法
     * @param {Function} func 要执行的方法
     * @param  {...any} args 参数
     * @returns {any} 成功执行的返回值
     */
    export function safeExecuteFunc (func, ...args) {
      if (typeof func === 'function') {
        try {
          return func(...args);
        } catch (err) {
          console.error(err);
        }
      } else {
        console.warn('func 不是可执行的方法!', func);
      }
      return undefined;
    }
    
    /**
     * 切换全屏显示状态
     * @param {Boolean} bFullScreen 指定切换状态
     */
    export function toggleFullScreen (bFullScreen) {
      if (bFullScreen === undefined) { // 未指定则取反
        bFullScreen = !(document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen);
      }
      var el = document.documentElement;
      if (bFullScreen) { // 进入全屏,多重短路表达式
        (el.requestFullscreen && el.requestFullscreen()) ||
            (el.mozRequestFullScreen && el.mozRequestFullScreen()) ||
            (el.webkitRequestFullscreen && el.webkitRequestFullscreen()) ||
            (el.msRequestFullscreen && el.msRequestFullscreen());
      } else { // 退出全屏
        const exitFullscreen = document.exitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen;
        exitFullscreen && exitFullscreen();
      }
      return bFullScreen;
    }
    
    export function dataURLtoBlob (dataurl) {
      var arr = dataurl.split(',');
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime
      });
    }
    
    /**
     * 查找当前属性值所在的对象
     * @param {Array} data 被查找对象数据
     * @param {String} findStr 查找属性名
     * @param {String} curVal 查找的属性值
     * @return {Object} 
     */
    export function recursionFunc(data, findStr, curVal) {
        let result = null;
        if (!data) {
          return
        }
        for (let i in data) {
          if (result !== null) {
            break
          }
          let item = data[i]
          if (item[findStr] == curVal) {
            result  = item;
            break
          } else if (item.children && item.children.length > 0) {
            result = this.recursionFunc(item.children, curVal)
          }
        }
        return result
      }
    /**
     * 删除指定空值的属性
     * @param {Array} data 查找属性名
     * @param {Array} curKey 查找属性名
     * @return {Array} 
     */
    export function handleRecur(data, curKey) {
        return data.reduce((iter, val) => {
            val[curKey].length ? val[curKey] = this.handleRecur(val[curKey]) : delete val[curKey];
            iter.push(val);
            return iter
        }, [])
    }
    

      

  • 相关阅读:
    如何在iTerm2中配置oh my zsh?
    sublime中格式化jsx文件
    ES6 new syntax of Literal
    ES6 new syntax of Rest and Spread Operators
    How to preview html file in our browser at sublime text?
    ES6 new syntax of Default Function Parameters
    ES6 new syntax of Arrow Function
    七牛云2018春招笔试题
    Spring-使用注解开发(十二)
    Spring-声明式事物(十一)
  • 原文地址:https://www.cnblogs.com/harlem/p/12849925.html
Copyright © 2011-2022 走看看