trtc-electron-sdk
Version:
trtc electron sdk
134 lines (133 loc) • 4.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.throttle = exports.debounce = exports.convertUint8ArrayToNumber = exports.safelyParse = exports.isNullOrUndefined = exports.isUndefined = exports.isNull = void 0;
function isNull(val) {
return val === null;
}
exports.isNull = isNull;
function isUndefined(val) {
return val === undefined;
}
exports.isUndefined = isUndefined;
function isNullOrUndefined(val) {
return val === null || val === undefined;
}
exports.isNullOrUndefined = isNullOrUndefined;
/**
* 安全执行 JSON.parse
* @param data
* @returns
*/
function safelyParse(data) {
if (typeof data !== 'string') {
return data;
}
let result;
try {
const tempData = JSON.parse(data);
// 规避 JSON.parse('12345') 转化为 12345 的情况
if (typeof tempData === 'object' && tempData) {
result = tempData;
}
else {
result = data;
}
}
catch (error) {
result = data;
}
return result;
}
exports.safelyParse = safelyParse;
function convertUint8ArrayToNumber(value) {
let result = 0;
for (let i = value.length - 1; i >= 0; i--) {
result = (result * 256) + value[i];
}
return result;
}
exports.convertUint8ArrayToNumber = convertUint8ArrayToNumber;
/**
* 防抖函数 (debounce)
*
* 适用场景:搜索框输入联想、窗口resize结束事件
*
* @param func 需要防抖的函数
* @param wait 等待时间(毫秒)
* @param immediate 是否立即执行第一次调用(true=立即执行,false=等待后执行)
* @returns 包装后的防抖函数
*/
function debounce(func, wait, immediate = false) {
let timeout = null;
let inWait = false; // 是否处于等待周期
return function (...args) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const context = this;
// 每次调用都清除现有定时器
if (timeout)
clearTimeout(timeout);
if (immediate && !inWait) {
// 立即执行模式且不在等待期
func.apply(context, args);
inWait = true;
}
// 设置新定时器
timeout = setTimeout(() => {
inWait = false;
if (!immediate) {
// 非立即执行模式:执行最后一次调用
func.apply(context, args);
}
}, wait);
};
}
exports.debounce = debounce;
/**
* 节流函数 (throttle)
*
* 适用场景:滚动事件、按钮防重复点击、鼠标移动事件
*
* @param func 需要节流的函数
* @param wait 等待时间(毫秒)
* @param options 配置选项
* leading: 是否执行第一次调用(true=执行,false=跳过)
* trailing: 是否执行最后一次调用(true=执行,false=跳过)
* @returns 包装后的节流函数
*/
function throttle(func, wait, options = {}) {
const { leading = true, trailing = true } = options;
let lastExecTime = 0;
let timer = null;
let savedContext = null, savedArgs = null;
// 实际执行函数
const execute = () => {
lastExecTime = Date.now();
timer = null;
if (savedContext !== null && savedArgs !== null) {
func.apply(savedContext, savedArgs);
}
};
return function (...args) {
savedContext = this;
savedArgs = args;
const now = Date.now();
// 计算距离上次执行的时间差
const sinceLast = now - lastExecTime;
const remaining = wait - sinceLast;
// 超时情况:立即执行(无论是否在等待期)
if (remaining <= 0 || remaining > wait) {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (leading) {
execute();
}
}
else if (!timer && trailing) {
// 设置定时器执行尾部调用
timer = setTimeout(execute, remaining);
}
};
}
exports.throttle = throttle;