B2B网络软件
标题:
AIWROK数组方法高级应用案例
[打印本页]
作者:
YYPOST群发软件
时间:
13 小时前
标题:
AIWROK数组方法高级应用案例
AIWROK数组方法高级应用案例
/**
* AIWROK数组方法高级应用案例
* 专为安卓Rhino JavaScript引擎优化的数组处理解决方案
* 🍎交流QQ群711841924群一,苹果内测群,528816639
* @功能特点
* - 完全兼容ES5语法和Rhino引擎
* - 提供数据过滤、转换、聚合等高级操作
* - 支持批量处理和异步操作模式
* - 集成AIWROK特有的日志和UI显示功能
* - 包含性能优化和内存管理
*
* @应用场景
* - UI控件批量操作
* - 网络请求数据处理
* - 图像识别结果筛选
* - 日志数据聚合分析
* - 多线程数据处理
*
* @作者 AIWROK开发团队
* @版本 1.0 - Rhino兼容版
* @日期 2024
*/
//===========================================
// 基础兼容性设置
//===========================================
// 确保printl函数可用(兼容Rhino环境)
if (typeof printl === 'undefined') {
function printl(message) {
try {
if (typeof console !== 'undefined' && console.log) {
console.log(message);
} else if (typeof print !== 'undefined') {
print(message);
} else {
java.lang.System.out.println(String(message));
}
} catch (e) {
// 静默失败
}
}
}
//===========================================
// 高级数组工具类
//===========================================
/**
* ArrayUtils - 高级数组操作工具类
* 提供链式调用、批量处理和性能优化功能
*/
function ArrayUtils() {
this.version = "1.0.0";
this.performanceMetrics = {
operations: 0,
startTime: 0,
endTime: 0
};
}
/**
* 开始性能监控
*/
ArrayUtils.prototype.startPerformanceMonitoring = function() {
this.performanceMetrics.startTime = new Date().getTime();
this.performanceMetrics.operations = 0;
return this;
};
/**
* 结束性能监控并返回报告
*/
ArrayUtils.prototype.endPerformanceMonitoring = function() {
this.performanceMetrics.endTime = new Date().getTime();
var duration = this.performanceMetrics.endTime - this.performanceMetrics.startTime;
return {
duration: duration,
operations: this.performanceMetrics.operations,
opsPerSecond: Math.round(this.performanceMetrics.operations / (duration / 1000))
};
};
/**
* 安全数组遍历 - 支持中断和异常处理
* @param {Array} array - 要遍历的数组
* @param {Function} callback - 回调函数,返回false可中断遍历
* @param {Object} context - 回调函数上下文
* @returns {ArrayUtils} 支持链式调用
*/
ArrayUtils.prototype.forEachSafe = function(array, callback, context) {
if (!Array.isArray(array)) throw new Error('参数必须是数组');
if (typeof callback !== 'function') throw new Error('回调函数必须是函数');
context = context || this;
try {
for (var i = 0; i < array.length; i++) {
this.performanceMetrics.operations++;
var result = callback.call(context, array[i], i, array);
if (result === false) break; // 支持主动中断
}
} catch (e) {
printl("数组遍历错误 at index " + i + ": " + (e.message || e));
}
return this;
};
/**
* 智能数组过滤 - 支持多条件和复杂逻辑
* @param {Array} array - 源数组
* @param {Array} conditions - 过滤条件数组
* @returns {Array} 过滤后的数组
*
* @示例
* var result = arrayUtils.smartFilter(data, [
* { field: 'age', operator: '>', value: 18 },
* { field: 'name', operator: 'contains', value: '张' },
* { field: 'score', operator: 'between', value: [60, 100] }
* ]);
*/
ArrayUtils.prototype.smartFilter = function(array, conditions) {
if (!Array.isArray(array)) throw new Error('第一个参数必须是数组');
if (!Array.isArray(conditions)) throw new Error('条件参数必须是数组');
var self = this;
return array.filter(function(item) {
self.performanceMetrics.operations++;
for (var i = 0; i < conditions.length; i++) {
var condition = conditions[i];
var fieldValue = self.getFieldValue(item, condition.field);
if (!self.evaluateCondition(fieldValue, condition.operator, condition.value)) {
return false;
}
}
return true;
});
};
/**
* 获取对象字段值 - 支持嵌套属性访问
*/
ArrayUtils.prototype.getFieldValue = function(obj, field) {
if (!obj || !field) return undefined;
var parts = field.split('.');
var result = obj;
for (var i = 0; i < parts.length; i++) {
if (result === null || result === undefined) return undefined;
result = result[parts[i]];
}
return result;
};
/**
* 评估条件 - 支持多种操作符
*/
ArrayUtils.prototype.evaluateCondition = function(fieldValue, operator, conditionValue) {
switch (operator) {
case '==': return fieldValue == conditionValue;
case '===': return fieldValue === conditionValue;
case '!=': return fieldValue != conditionValue;
case '!==': return fieldValue !== conditionValue;
case '>': return fieldValue > conditionValue;
case '>=': return fieldValue >= conditionValue;
case '<': return fieldValue < conditionValue;
case '<=': return fieldValue <= conditionValue;
case 'contains':
return String(fieldValue).indexOf(conditionValue) !== -1;
case 'startsWith':
return String(fieldValue).indexOf(conditionValue) === 0;
case 'endsWith':
var str = String(fieldValue);
return str.lastIndexOf(conditionValue) === str.length - conditionValue.length;
case 'between':
return fieldValue >= conditionValue[0] && fieldValue <= conditionValue[1];
case 'in':
return conditionValue.indexOf(fieldValue) !== -1;
case 'notIn':
return conditionValue.indexOf(fieldValue) === -1;
default:
return false;
}
};
/**
* 数组数据聚合 - 支持多种聚合函数
* @param {Array} array - 源数组
* @param {Object} config - 聚合配置
* @returns {Object} 聚合结果
*
* @示例
* var stats = arrayUtils.aggregate(salesData, {
* groupBy: 'category',
* metrics: {
* totalSales: { field: 'amount', operation: 'sum' },
* avgPrice: { field: 'price', operation: 'avg' },
* count: { operation: 'count' }
* }
* });
*/
ArrayUtils.prototype.aggregate = function(array, config) {
if (!Array.isArray(array)) throw new Error('参数必须是数组');
var result = {};
var self = this;
// 分组处理
if (config.groupBy) {
var groups = {};
array.forEach(function(item) {
self.performanceMetrics.operations++;
var groupKey = self.getFieldValue(item, config.groupBy);
if (!groups[groupKey]) {
groups[groupKey] = [];
}
groups[groupKey].push(item);
});
// 对每个分组进行聚合
for (var groupKey in groups) {
if (groups.hasOwnProperty(groupKey)) {
result[groupKey] = self.calculateMetrics(groups[groupKey], config.metrics);
}
}
} else {
// 不分组,直接聚合
result = this.calculateMetrics(array, config.metrics);
}
return result;
};
/**
* 计算指标 - 支持多种聚合操作
*/
ArrayUtils.prototype.calculateMetrics = function(array, metrics) {
var result = {};
var self = this;
for (var metricName in metrics) {
if (metrics.hasOwnProperty(metricName)) {
var metric = metrics[metricName];
result[metricName] = self.calculateMetric(array, metric);
}
}
return result;
};
/**
* 计算单个指标
*/
ArrayUtils.prototype.calculateMetric = function(array, metric) {
var operation = metric.operation;
var field = metric.field;
switch (operation) {
case 'count':
return array.length;
case 'sum':
return array.reduce(function(sum, item) {
return sum + (field ? this.getFieldValue(item, field) : item);
}.bind(this), 0);
case 'avg':
var sum = array.reduce(function(sum, item) {
return sum + (field ? this.getFieldValue(item, field) : item);
}.bind(this), 0);
return array.length > 0 ? sum / array.length : 0;
case 'max':
return Math.max.apply(Math, array.map(function(item) {
return field ? this.getFieldValue(item, field) : item;
}.bind(this)));
case 'min':
return Math.min.apply(Math, array.map(function(item) {
return field ? this.getFieldValue(item, field) : item;
}.bind(this)));
default:
return 0;
}
};
/**
* 数组分页处理 - 支持大数据集的分页显示
* @param {Array} array - 源数组
* @param {number} pageSize - 每页大小
* @param {number} pageNumber - 页码(从1开始)
* @returns {Object} 分页结果
*/
ArrayUtils.prototype.paginate = function(array, pageSize, pageNumber) {
if (!Array.isArray(array)) throw new Error('参数必须是数组');
pageSize = Math.max(1, pageSize || 10);
pageNumber = Math.max(1, pageNumber || 1);
var totalItems = array.length;
var totalPages = Math.ceil(totalItems / pageSize);
var startIndex = (pageNumber - 1) * pageSize;
var endIndex = Math.min(startIndex + pageSize, totalItems);
return {
items: array.slice(startIndex, endIndex),
pagination: {
pageNumber: pageNumber,
pageSize: pageSize,
totalItems: totalItems,
totalPages: totalPages,
hasPrevious: pageNumber > 1,
hasNext: pageNumber < totalPages,
startIndex: startIndex,
endIndex: endIndex - 1
}
};
};
/**
* 数组去重 - 支持复杂对象的去重
* @param {Array} array - 源数组
* @param {string|Function} keySelector - 用于去重的键选择器
* @returns {Array} 去重后的数组
*/
ArrayUtils.prototype.distinct = function(array, keySelector) {
if (!Array.isArray(array)) throw new Error('参数必须是数组');
var seen = {};
var result = [];
var self = this;
array.forEach(function(item) {
self.performanceMetrics.operations++;
var key;
if (typeof keySelector === 'function') {
key = keySelector(item);
} else if (typeof keySelector === 'string') {
key = self.getFieldValue(item, keySelector);
} else {
key = item;
}
var keyString = String(key);
if (!seen.hasOwnProperty(keyString)) {
seen[keyString] = true;
result.push(item);
}
});
return result;
};
//===========================================
// AIWROK特定功能集成
//===========================================
/**
* UI控件批量处理 - 结合AIWROK的UI操作
* @param {Array} uiElements - UI元素数组
* @param {Function} processor - 处理函数
* @param {Object} options - 处理选项
*/
ArrayUtils.prototype.batchUIProcess = function(uiElements, processor, options) {
options = options || {};
var batchSize = options.batchSize || 10;
var delay = options.delay || 100;
var self = this;
printl("开始批量处理 " + uiElements.length + " 个UI元素");
var batches = [];
for (var i = 0; i < uiElements.length; i += batchSize) {
batches.push(uiElements.slice(i, i + batchSize));
}
// 分批处理
batches.forEach(function(batch, batchIndex) {
setTimeout(function() {
printl("处理第 " + (batchIndex + 1) + " 批,共 " + batch.length + " 个元素");
batch.forEach(function(element, index) {
try {
processor(element, index);
self.performanceMetrics.operations++;
} catch (e) {
printl("处理UI元素失败: " + (e.message || e));
}
});
if (batchIndex === batches.length - 1) {
printl("批量处理完成");
}
}, batchIndex * delay);
});
return this;
};
/**
* OCR结果智能筛选 - 结合AIWROK的OCR功能
* @param {Array} ocrResults - OCR识别结果数组
* @param {Object} filterOptions - 筛选选项
* @returns {Array} 筛选后的结果
*/
ArrayUtils.prototype.filterOCRResults = function(ocrResults, filterOptions) {
filterOptions = filterOptions || {};
var conditions = [];
// 文本长度过滤
if (filterOptions.minLength) {
conditions.push({
field: 'text',
operator: '>',
value: filterOptions.minLength
});
}
// 置信度过滤
if (filterOptions.minConfidence) {
conditions.push({
field: 'confidence',
operator: '>=',
value: filterOptions.minConfidence
});
}
// 文本内容过滤
if (filterOptions.contains) {
conditions.push({
field: 'text',
operator: 'contains',
value: filterOptions.contains
});
}
// 位置过滤
if (filterOptions.minX !== undefined) {
conditions.push({
field: 'x',
operator: '>=',
value: filterOptions.minX
});
}
return this.smartFilter(ocrResults, conditions);
};
/**
* 日志数据聚合分析 - 结合AIWROK的日志功能
* @param {Array} logEntries - 日志条目数组
* @param {Object} analysisConfig - 分析配置
* @returns {Object} 分析结果
*/
ArrayUtils.prototype.analyzeLogs = function(logEntries, analysisConfig) {
analysisConfig = analysisConfig || {};
var timeWindow = analysisConfig.timeWindow || 3600000; // 1小时
var logLevelWeights = analysisConfig.logLevelWeights || {
'ERROR': 10,
'WARN': 5,
'INFO': 1,
'DEBUG': 0.5
};
var currentTime = new Date().getTime();
var recentLogs = logEntries.filter(function(log) {
return currentTime - log.timestamp <= timeWindow;
});
var analysis = {
totalLogs: recentLogs.length,
levelDistribution: {},
errorRate: 0,
warningRate: 0,
healthScore: 100
};
// 统计日志级别分布
recentLogs.forEach(function(log) {
var level = log.level || 'INFO';
analysis.levelDistribution[level] = (analysis.levelDistribution[level] || 0) + 1;
});
// 计算错误率和警告率
var errorCount = analysis.levelDistribution['ERROR'] || 0;
var warnCount = analysis.levelDistribution['WARN'] || 0;
analysis.errorRate = analysis.totalLogs > 0 ? (errorCount / analysis.totalLogs) * 100 : 0;
analysis.warningRate = analysis.totalLogs > 0 ? (warnCount / analysis.totalLogs) * 100 : 0;
// 计算健康分数
var totalWeight = 0;
var weightedScore = 0;
for (var level in analysis.levelDistribution) {
if (analysis.levelDistribution.hasOwnProperty(level)) {
var count = analysis.levelDistribution[level];
var weight = logLevelWeights[level] || 1;
totalWeight += count * weight;
weightedScore += count * weight;
}
}
if (totalWeight > 0) {
analysis.healthScore = Math.max(0, 100 - (errorCount * 10) - (warnCount * 3));
}
return analysis;
};
//===========================================
// 使用示例和测试
//===========================================
function ecommerceDataProcessingExample() {
printl("=== AIWROK数组方法高级应用案例 ===");
// 创建数组工具实例
var arrayUtils = new ArrayUtils();
// 模拟电商数据
var products = [
{ id: 1, name: 'iPhone 13', category: '手机', price: 5999, stock: 50, sales: 120 },
{ id: 2, name: '华为P50', category: '手机', price: 4488, stock: 30, sales: 85 },
{ id: 3, name: 'MacBook Pro', category: '电脑', price: 12999, stock: 20, sales: 45 },
{ id: 4, name: '小米电视', category: '家电', price: 2999, stock: 15, sales: 200 },
{ id: 5, name: 'AirPods Pro', category: '配件', price: 1999, stock: 100, sales: 300 },
{ id: 6, name: '华为手表', category: '配件', price: 2688, stock: 25, sales: 150 },
{ id: 7, name: 'iPad Air', category: '平板', price: 4399, stock: 40, sales: 180 },
{ id: 8, name: '戴尔显示器', category: '电脑', price: 2199, stock: 35, sales: 95 }
];
// 开始性能监控
arrayUtils.startPerformanceMonitoring();
printl("原始数据:共 " + products.length + " 个商品");
// 1. 智能筛选:找出价格大于2000且销量大于100的商品
var hotProducts = arrayUtils.smartFilter(products, [
{ field: 'price', operator: '>', value: 2000 },
{ field: 'sales', operator: '>', value: 100 }
]);
printl("热门商品:" + hotProducts.length + " 个");
hotProducts.forEach(function(product) {
printl(" - " + product.name + " (价格: ¥" + product.price + ", 销量: " + product.sales + ")");
});
// 2. 数据聚合:按类别统计
var categoryStats = arrayUtils.aggregate(products, {
groupBy: 'category',
metrics: {
totalProducts: { operation: 'count' },
avgPrice: { field: 'price', operation: 'avg' },
totalSales: { field: 'sales', operation: 'sum' },
totalValue: { field: 'stock', operation: 'sum' }
}
});
printl("\n类别统计:");
for (var category in categoryStats) {
if (categoryStats.hasOwnProperty(category)) {
var stats = categoryStats[category];
printl(" " + category + ": ");
printl(" 商品数量: " + stats.totalProducts);
printl(" 平均价格: ¥" + Math.round(stats.avgPrice));
printl(" 总销量: " + stats.totalSales);
printl(" 库存总量: " + stats.totalValue);
}
}
// 3. 分页显示:每页显示3个商品
var pageResult = arrayUtils.paginate(products, 3, 2);
printl("\n分页显示(第2页,每页3个):");
pageResult.items.forEach(function(product) {
printl(" " + product.name + " - " + product.category);
});
printl("分页信息:");
printl(" 当前页: " + pageResult.pagination.pageNumber);
printl(" 总页数: " + pageResult.pagination.totalPages);
printl(" 总商品数: " + pageResult.pagination.totalItems);
// 4. 复杂数据处理示例:找出各品类中最畅销的商品
var topProductsByCategory = {};
var categories = arrayUtils.distinct(products, 'category');
categories.forEach(function(category) {
var categoryProducts = arrayUtils.smartFilter(products, [
{ field: 'category', operator: '==', value: category }
]);
// 按销量排序,取销量最高的
categoryProducts.sort(function(a, b) {
return b.sales - a.sales;
});
// 确保分类下有商品再赋值
if (categoryProducts.length > 0) {
topProductsByCategory[category] = categoryProducts[0];
}
});
printl("\n各品类最畅销商品:");
for (var cat in topProductsByCategory) {
if (topProductsByCategory.hasOwnProperty(cat)) {
var product = topProductsByCategory[cat];
if (product) { // 确保产品存在再输出
printl(" " + cat + ": " + product.name + " (销量: " + product.sales + ")");
}
}
}
// 5. 性能监控结果
var perfReport = arrayUtils.endPerformanceMonitoring();
printl("\n性能报告:");
printl(" 执行时间: " + perfReport.duration + "ms");
printl(" 操作次数: " + perfReport.operations);
printl(" 处理速度: " + perfReport.opsPerSecond + " ops/sec");
}
/**
* OCR识别结果处理示例
*/
function ocrResultProcessingExample() {
printl("\n=== OCR识别结果处理示例 ===");
var arrayUtils = new ArrayUtils();
// 模拟OCR识别结果
var ocrResults = [
{ text: '登录', confidence: 0.95, x: 100, y: 200, width: 50, height: 30 },
{ text: '用户名', confidence: 0.87, x: 50, y: 300, width: 70, height: 25 },
{ text: '密码', confidence: 0.92, x: 50, y: 350, width: 50, height: 25 },
{ text: '记住我', confidence: 0.78, x: 100, y: 400, width: 80, height: 20 },
{ text: '忘记密码', confidence: 0.85, x: 200, y: 400, width: 90, height: 20 },
{ text: '注册', confidence: 0.90, x: 300, y: 200, width: 50, height: 30 },
{ text: 'AIWROK', confidence: 0.98, x: 150, y: 100, width: 100, height: 40 },
{ text: '帮助', confidence: 0.72, x: 300, y: 500, width: 50, height: 25 }
];
// 筛选高置信度文本
var highConfidenceTexts = arrayUtils.filterOCRResults(ocrResults, {
minConfidence: 0.85
});
printl("高置信度文本 (" + highConfidenceTexts.length + " 个):");
highConfidenceTexts.forEach(function(result) {
printl(" - " + result.text + " (置信度: " + result.confidence + ")");
});
// 查找特定关键词
var loginRelatedTexts = arrayUtils.filterOCRResults(ocrResults, {
contains: '登录'
});
printl("\n包含'登录'的文本:");
loginRelatedTexts.forEach(function(result) {
printl(" - " + result.text);
});
}
/**
* 日志分析示例
*/
function logAnalysisExample() {
printl("\n=== 日志分析示例 ===");
var arrayUtils = new ArrayUtils();
// 模拟日志数据
var logEntries = [
{ level: 'INFO', message: '应用启动', timestamp: new Date().getTime() - 3600000 },
{ level: 'DEBUG', message: '加载配置文件', timestamp: new Date().getTime() - 3590000 },
{ level: 'INFO', message: '用户登录成功', timestamp: new Date().getTime() - 3500000 },
{ level: 'WARN', message: '内存使用率过高', timestamp: new Date().getTime() - 3000000 },
{ level: 'ERROR', message: '数据库连接失败', timestamp: new Date().getTime() - 2500000 },
{ level: 'INFO', message: '数据库连接恢复', timestamp: new Date().getTime() - 2400000 },
{ level: 'ERROR', message: 'API请求超时', timestamp: new Date().getTime() - 2000000 },
{ level: 'WARN', message: 'API响应缓慢', timestamp: new Date().getTime() - 1800000 },
{ level: 'INFO', message: '用户执行操作', timestamp: new Date().getTime() - 1500000 },
{ level: 'DEBUG', message: '缓存更新', timestamp: new Date().getTime() - 1000000 }
];
// 分析最近一小时的日志
var analysis = arrayUtils.analyzeLogs(logEntries, {
timeWindow: 3600000, // 1小时
logLevelWeights: {
'ERROR': 10,
'WARN': 5,
'INFO': 1,
'DEBUG': 0.5
}
});
printl("日志分析结果:");
printl(" 总日志数: " + analysis.totalLogs);
printl(" 错误率: " + analysis.errorRate.toFixed(2) + "%");
printl(" 警告率: " + analysis.warningRate.toFixed(2) + "%");
printl(" 系统健康评分: " + analysis.healthScore);
printl(" 日志级别分布:");
for (var level in analysis.levelDistribution) {
if (analysis.levelDistribution.hasOwnProperty(level)) {
printl(" " + level + ": " + analysis.levelDistribution[level]);
}
}
}
/**
* UI元素批量处理示例
*/
function uiElementBatchProcessingExample() {
printl("\n=== UI元素批量处理示例 ===");
var arrayUtils = new ArrayUtils();
// 模拟UI元素
var uiElements = [
{ id: 'btn1', type: 'button', text: '提交', visible: true },
{ id: 'btn2', type: 'button', text: '取消', visible: true },
{ id: 'inp1', type: 'input', text: '', visible: true },
{ id: 'inp2', type: 'input', text: '', visible: false },
{ id: 'chk1', type: 'checkbox', text: '同意条款', visible: true },
{ id: 'lbl1', type: 'label', text: '用户协议', visible: true },
{ id: 'img1', type: 'image', text: '', visible: true }
];
// 处理可见的按钮元素
var visibleButtons = arrayUtils.smartFilter(uiElements, [
{ field: 'visible', operator: '==', value: true },
{ field: 'type', operator: '==', value: 'button' }
]);
printl("可见按钮数量: " + visibleButtons.length);
// 模拟批量处理
arrayUtils.batchUIProcess(visibleButtons, function(element, index) {
try {
printl(" 处理按钮 #" + (index+1) + ": " + element.text + " (ID: " + element.id + ")");
// 这里可以执行实际的UI操作,如点击、修改属性等
} catch (e) {
printl(" 处理按钮时出错: " + e.message);
}
}, { batchSize: 2, delay: 500 });
}
//===========================================
// 主函数和执行入口
//===========================================
/**
* 运行所有示例
*/
function runAllExamples() {
try {
ecommerceDataProcessingExample();
ocrResultProcessingExample();
logAnalysisExample();
uiElementBatchProcessingExample();
printl("\n=== 所有示例执行完成 ===");
} catch (e) {
printl("执行示例时发生错误: " + (e.message || e));
}
}
// 如果直接运行此脚本,则执行所有示例
if (typeof module === 'undefined' || !module.exports) {
runAllExamples();
}
// 导出ArrayUtils类供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
module.exports = ArrayUtils;
}
复制代码
欢迎光临 B2B网络软件 (http://bbs.niubt.cn/)
Powered by Discuz! X3.2