bridgecrate
Version:
一个提供数据传输和桥接功能的JavaScript工具包
108 lines (97 loc) • 2.71 kB
JavaScript
// BridgeCrate - 数据传输和桥接工具包
/**
* 主要的摆渡功能,用于处理和传输数据
* @param {any} data - 需要摆渡的数据
* @param {Object} options - 配置选项
* @returns {Promise<any>} 处理后的数据
*/
async function bridge(data, options = {}) {
try {
// 模拟异步处理
await new Promise(resolve => setTimeout(resolve, 10));
// 基础数据处理逻辑
if (typeof data === 'object' && data !== null) {
return {
...data,
timestamp: Date.now(),
processed: true,
...options
};
}
return {
data,
timestamp: Date.now(),
processed: true,
...options
};
} catch (error) {
throw new Error(`Bridge processing failed: ${error.message}`);
}
}
/**
* 数据转换器,使用提供的转换函数处理输入数据
* @param {any} input - 输入数据
* @param {Function} transformer - 转换函数
* @returns {any} 转换后的数据
*/
function transform(input, transformer) {
if (typeof transformer !== 'function') {
throw new Error('Transformer must be a function');
}
try {
return transformer(input);
} catch (error) {
throw new Error(`Transform failed: ${error.message}`);
}
}
/**
* 工具函数集合
*/
const utils = {
/**
* 检查数据是否为空
* @param {any} data - 要检查的数据
* @returns {boolean} 是否为空
*/
isEmpty(data) {
if (data === null || data === undefined) return true;
if (typeof data === 'string') return data.trim() === '';
if (Array.isArray(data)) return data.length === 0;
if (typeof data === 'object') return Object.keys(data).length === 0;
return false;
},
/**
* 深拷贝对象
* @param {any} obj - 要拷贝的对象
* @returns {any} 拷贝后的对象
*/
deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (obj instanceof Date) return new Date(obj.getTime());
if (obj instanceof Array) return obj.map(item => this.deepClone(item));
if (typeof obj === 'object') {
const cloned = {};
Object.keys(obj).forEach(key => {
cloned[key] = this.deepClone(obj[key]);
});
return cloned;
}
return obj;
},
/**
* 延迟执行
* @param {number} ms - 延迟毫秒数
* @returns {Promise<void>} Promise对象
*/
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
};
// CommonJS 导出
module.exports = {
bridge,
transform,
utils
};
// 默认导出
module.exports.default = { bridge, transform, utils };