解题思路:

  • 读取操作字符串,拆分成数组
  • 依次处理每一个 action,使用 reduce 的时候注意传初始化坐标 [0,0]
  • 通过正则表达式去检查 action 是否有效,无效则跳过当前元素!通过获取匹配捕获组得到移动方向和值
  • 更新坐标
  • 输出结果
const actionArr = readline().split(';');
const result = actionArr.reduce((initCoordinate, curAction) => {
    if(/^([ASDW]{1})(\d{1,2})$/.test(curAction)) {
        const action = RegExp.$1;
        const val = ~~RegExp.$2;
        let [x, y] = initCoordinate;
        if(action === 'A') {
            x -= val;
        } else if(action === 'D') {
            x += val;
        } else if(action === 'S') {
            y -= val;
        } else {
            y += val;
        }
        return [x, y];
    }
    return initCoordinate;
}, [0, 0])
console.log(result.join(','));