utils.js 1.32 KB
import md5 from 'yoho-md5';
import * as signUtils from 'utils/sign.js';

export const getImgUrl = function(src, width = 300, height = 300, mode = 2) {
  return src ? src.replace(/(\{width}|\{height}|\{mode})/g, function($0) {
    const dict = {
      '{width}': width,
      '{height}': height,
      '{mode}': mode || 2
    };

    return dict[$0];
  }).replace(/https?:/, '') + '/interlace/1' : '';
};


export const replaceHttp = function(src) {
  return src.replace(/https?:/, '');
};


export const debounce = (idle, action) => { // 函数去抖动,超过一定时间才会执行,如果周期内触发,充值计时器
  let last;

  return function() {
    let args = arguments;

    if (last) {
      clearTimeout(last);
    }
    last = setTimeout(() => {
      action.apply(this, args);
    }, idle);
  };
};


export const throttle = (delay, action) => { // 函数节流器,定义函数执行间隔,按频率触发函数
  let last = 0;

  return function() {
    let args = arguments;
    let curr = +new Date();

    if (curr - last > delay) {
      action.apply(this, args);
      last = curr;
    }
  };
};

export const sign = (op) => {
  const p = signUtils.getParams(op);

  signUtils.setTime(p);

  const str = `${signUtils.joinParams(p, signUtils.sortParams(p))}`;

  signUtils.setSign(p, md5(`${str}_${str.length}`));
};