[JavaScript] 纯文本查看 复制代码 class NumberMonitor {
constructor() {
this.hasReceivedLow = false; // 是否收到过小于130的数字
this.lastValue = null; // 上一次收到的数字
this.isRising = false; // 当前是否处于上升趋势
}
processNumber(num) {
console.log(`收到数字: ${num}`);
// 检查是否收到过小于130的数字
if (num < 130) {
this.hasReceivedLow = true;
console.log(`收到低值数字 ${num},已标记`);
}
// 检测趋势变化
if (this.lastValue !== null) {
if (num > this.lastValue) {
if (!this.isRising) {
console.log('检测到开始上升趋势');
}
this.isRising = true;
} else if (num < this.lastValue) {
if (this.isRising) {
console.log('上升趋势结束');
}
this.isRising = false;
}
}
this.checkAlert(num);
this.lastValue = num;
}
checkAlert(num) {
// 只有在140-150范围内,且有过低值数字,且处于上升趋势时才提示
if (num >= 140 && num <= 150) {
if (this.hasReceivedLow && this.isRising) {
console.log(`数字 ${num} 在140-150范围内`);
this.showAlert(num);
} else if (!this.hasReceivedLow) {
console.log(` 数字 ${num} 在范围内,但未收到过小于130的数字`);
} else if (!this.isRising) {
console.log(` 数字 ${num} 在范围内,但不是上升趋势`);
}
}
}
showAlert(num) {
alert(`:数字 ${num} 达到140-150范围!`);
}
// 重置状态(如果需要重新开始监控)
reset() {
this.hasReceivedLow = false;
this.lastValue = null;
this.isRising = false;
console.log('监控状态已重置');
}
}
// 使用示例
const monitor = new NumberMonitor();
// 模拟WebSocket消息处理
function simulateWebSocket() {
// 模拟从高到低的情况(不应该触发警报)
const descendingSequence = [200, 195, 185, 175, 160, 155, 150, 145];
// 模拟先降后升的情况(应该触发警报)
const risingSequence = [110, 120, 125, 130, 135, 140, 145, 150];
console.log('=== 测试1: 从高到低===');
descendingSequence.forEach((num, index) => {
setTimeout(() => monitor.processNumber(num), index * 200);
});
setTimeout(() => {
console.log('\n=== 重置状态 ===');
monitor.reset();
console.log('\n=== 测试2: 先降后升===');
risingSequence.forEach((num, index) => {
setTimeout(() => monitor.processNumber(num), index * 200);
});
}, descendingSequence.length * 200 + 500);
}
// 实际的WebSocket处理函数
function setupWebSocket() {
const ws = new WebSocket('wss://your-websocket-url');
ws.onopen = function() {
console.log('WebSocket连接已建立');
};
ws.onmessage = function(event) {
try {
const num = parseInt(event.data);
if (!isNaN(num)) {
monitor.processNumber(num);
} else {
console.warn('收到非数字消息:', event.data);
}
} catch (error) {
console.error('处理消息时出错:', error);
}
};
ws.onclose = function() {
console.log('WebSocket连接已关闭');
};
ws.onerror = function(error) {
console.error('WebSocket错误:', error);
};
}
// 启动模拟测试
simulateWebSocket();
// 实际使用时,取消注释下面这行,并注释掉 simulateWebSocket()
// setupWebSocket(); |