• 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
        }, [])
    }
    

      

  • 相关阅读:
    企业库应用实践系列五:创建模板引擎Library
    关于HtmlHelper:是MVC自作聪明,还是我不够明白?
    企业库应用实践系列二:对象创建原理详解
    企业库应用实践系列三:自定义构造函数
    专业导论 计算机科学概论
    企业短期项目,缺人手
    光脚丫学LINQ(040):引发未将对象引用设置到对象的实例的异常
    光脚丫学LINQ(045):如何表示计算所得列(LINQ to SQL)
    光脚丫学LINQ(042):如何将列表示为由数据库生成的列
    光脚丫学LINQ(043):为实体类的列成员指定在数据库中的数据类型
  • 原文地址:https://www.cnblogs.com/harlem/p/12849925.html
Copyright © 2020-2023  润新知