You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现processOrderList订单列表状态处理函数需求

功能需求

processOrderList 函数接收3个入参:订单对象数组 OrderList、数字类型 OrderId、仅可取 "Processing" 或 "Delivered" 值的字符串类型 State,需按规则更新订单列表并返回结果:

  • 若State为"Processing",将列表中id等于OrderId的订单的state属性更新为"Processing"
  • 若State为"Delivered",将列表中id等于OrderId的订单从列表中删除
  • 若不存在对应OrderId的订单,直接返回原OrderList
现有代码框架
'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding("ascii");
let inputString = "";
let currentLine = 0;

process.stdin.on("data", function(chunk) {
  inputString += chunk;
});
process.stdin.on("end", function() {
  inputString = inputString.split('\n');
  main();
});

function readLine() {
  return inputString[currentLine++];
}


function processOrderList(orderList, orderId, state) {
  // Write your code here
  console.log(orderId);
  console.log(orderList);
  console.log(state);

}


function main() {
  const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

  const orderCount = parseInt(readLine().trim());
  let orderList = [];
  for (let i = 0; i < orderCount; i++) {
    orderList.push({
      id: i + 1,
      state: 'Received'
    })
  };

  let numberOfOperations = parseInt(readLine().trim());
  let updatedOrderList = [...orderList];
  while (numberOfOperations-- > 0) {
    const inputs = readLine().trim().split(' ');
    const orderId = parseInt(inputs[0]);
    const updatedState = inputs[1];

    updatedOrderList = processOrderList(updatedOrderList, orderId, updatedState);
    updatedOrderList = [...updatedOrderList];
  }

  if (updatedOrderList.length > 0) {
    for (let i = 0; i < updatedOrderList.length; i++) {
      const order = updatedOrderList[i];
      ws.write(`Order with id ${order.id} is in ${order.state} state\n`);
    };
  } else {
    ws.write(`All orders are in Delivered state\n`);
  }

  ws.end();
}
processOrderList 函数实现代码

直接替换原函数内容即可:

function processOrderList(orderList, orderId, state) {
  if (state === 'Processing') {
    // 遍历订单数组,匹配到对应ID则更新state,其余保持不变
    return orderList.map(order => 
      order.id === orderId ? { ...order, state: 'Processing' } : order
    )
  } else if (state === 'Delivered') {
    // 过滤掉对应ID的订单
    return orderList.filter(order => order.id !== orderId)
  }
  // 兜底逻辑,非正常state入参直接返回原数组
  return orderList
}

实现说明

  • 全程操作返回新数组,不会修改传入的原订单数组,符合不可变要求,和现有代码框架里的数组展开操作逻辑适配
  • 当不存在对应ID的订单时,map/filter操作返回的数组内容和原数组完全一致,满足需求
  • 时间复杂度为O(n),适配绝大多数订单列表规模的使用场景

内容的提问来源于stack exchange,提问作者deveop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:54:02