/**
 * @export 函数节流:设置一个可执行状态,interval时间内不再调用就触发fn
 */
export function throttle (fn, interval = 200, scope) {
  let status = false;
  return function () {
    if (status) return;
    status = true;
    fn.apply(scope || this, arguments);
    setTimeout(() => {
      status = false;
    }, interval);
  };
}

///// handle: debounce(function() { })

/**
 * @export 函数防抖:每次调用重置计时器,delay时间内不再调用就触发fn
 */
export function debounce (fn, delay = 200, scope) {
  let timer = null;
  return function () {
    let context = scope || this,
      args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}

/**
 * @export 抽取集合内对象指定属性合并为新对象:序列化table组件表头数据
 */
export function serializeTableHeader (list, field, initial) {
  return list.reduce((acc, cur) => {
    const prop = cur[field];
    if (prop) acc[prop] = undefined;
    return acc;
  }, initial); // 设置初始值, 从0开始 reduce
}

/**
 * @export 组件table映射必须属性,避免注入无效依赖属性
 */
export function mapTableProperty (res, initial) {
  return res.map(item => {
    const obj = {};
    Object.keys(initial).forEach(prop => {
      obj[prop] = item?.[prop] ?? "";
    });
    return obj;
  });
}
